javascript - What's the best way to determine a route's template based on $cookies value in AngularJS? -


i'd root url, /, of angularjs app display template based on cookie value. example, when login cookie present display dashboard. when login cookie absent, display login screen.

i tried inject $cookies app.config determine template property of $route based on it, didn't work.

var myapp = angular.module('myapp', ['ngroute', 'ngcookies']); myapp.config([     '$routeprovider',     '$locationprovider',     function ($routeprovider, $locationprovider) {         $routeprovider.             when('/', {                 templateurl: function() {                     // read cookies here?                     return '../../connect.html';                 },                 controller: "getauthurl"             });         $locationprovider.             html5mode(true).             hashprefix('!');     } ]); 

answering own question...

after further investigation, found out $routeprovider not should using. $routeprovider serving templates based on url routes. problem needed ui-router module, official angularjs module.

instead of urls, ui-router lets specify page content based on "state". in situation, have "loggedin" state , "dashboard" state. here's how have implemented solution:

var myapp = angular.module('myapp', ['ngcookies', 'ui.router']);  myapp.config([     '$stateprovider',     '$locationprovider',     function ($stateprovider, $locationprovider) {         $stateprovider.             state('login', {                 template: '<h1>login now.</h1>'             }).state('dashboard', {                 template: '<h1>you logged in. welcome.</h1>'             });         $locationprovider.             html5mode(true).             hashprefix('!');     } ]);   myapp.controller('mainctrl', [     '$scope',     '$state',     '$cookies',     function($scope, $state, $cookies) {         // can read cookies here         if (true) {             console.log($cookies);             $state.go('dashboard');         }         else {             $state.go('login');         }     } ]); 

and html is

<!doctype html> <html ng-app='myapp'> <head>     <script src='js/lib/angular.js'></script>     <script src='js/lib/angular-ui-router.js'></script>     <script src='js/lib/angular-cookies.js'></script>     <script src="js/app.js"></script> </head> <body ng-controller='mainctrl'>  <div class="container" ui-view></div>  </body> </html> 

you can read ui-router in wiki

note: have use ui-router v0.0.2 @ least. v0.0.1 won't work.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -