what specific changes need made angularjs code below check existence of cookie named mycookie
every time page loaded, , set $rootscope.mycookievalue
variable become value of mycookie
?
the code the sample app complete code can explore @ link. simple example app, , want simple working solution can build more complex approaches it.
angular.module('hello', [ 'ngroute' ]).config(function($routeprovider, $httpprovider) { $routeprovider.when('/', { templateurl : 'home.html', controller : 'home', controlleras : 'controller' }).otherwise('/'); $httpprovider.defaults.headers.common['x-requested-with'] = 'xmlhttprequest'; $httpprovider.defaults.headers.common['accept'] = 'application/json'; }).controller('navigation', function($rootscope, $http, $location, $route) { var self = this; self.tab = function(route) { return $route.current && route === $route.current.controller; }; $http.get('user').then(function(response) { if (response.data.name) { $rootscope.authenticated = true; } else { $rootscope.authenticated = false; } }, function() { $rootscope.authenticated = false; }); self.credentials = {}; self.logout = function() { $http.post('logout', {}).finally(function() { $rootscope.authenticated = false; $location.path("/"); }); } }).controller('home', function($http) { var self = this; $http.get('resource/').then(function(response) { self.greeting = response.data; }) });
you can in run block guess:
angular.module('hello', ['ngcookies', 'ngroute']) .config(function ($routeprovider, $httpprovider) { $routeprovider.when('/', { templateurl: 'home.html', controller: 'home', controlleras: 'controller' }).otherwise('/'); $httpprovider.defaults.headers.common['x-requested-with'] = 'xmlhttprequest'; $httpprovider.defaults.headers.common['accept'] = 'application/json'; }).run(function ($rootscope, $cookies) { var cookievalue = $cookies.get("mycookie"); if (cookievalue) { $rootscope.mycookievar = cookievalue; } }).controller('navigation', function ($rootscope, $http, $location, $route) { var self = this; self.tab = function (route) { return $route.current && route === $route.current.controller; }; $http.get('user').then(function (response) { if (response.data.name) { $rootscope.authenticated = true; } else { $rootscope.authenticated = false; } }, function () { $rootscope.authenticated = false; }); self.credentials = {}; self.logout = function () { $http.post('logout', {}).finally(function () { $rootscope.authenticated = false; $location.path("/"); }); } }).controller('home', function ($http) { var self = this; $http.get('resource/').then(function (response) { self.greeting = response.data; }) });
i think should use angular version > 1.4.x
you should add reference angular-cookies.js
Comments
Post a Comment