我创建了一个函数来验证Cookie是否存在,并且我想使用
angularjs在每个页面中运行此函数.我似乎无法使该函数运行.我应该把它放在一个新的控制器上吗?
这是我达到了多远
angular.module('myApp',['ngCookies']).
config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/products',{templateUrl: '/tmpl/products.html',controller: Ctrl}).
otherwise({redirectTo: '/index'})
}]).run( function($rootScope,$location) {
//should I call it here?
//validateCookie();
});
function validateCookie($scope,$cookieStore,$http){
}
解决方法
我认为有几种方法来解决这个问题.如果您想要在每次更改路由时发生此验证(这意味着它将在应用程序首次启动时以及在应用程序中的每个页面上运行),您可以执行以下操作:
angular.module('myApp',['ngCookies']).
config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/index',{templateUrl: '/tmpl/index.html',controller: IndexCtrl}).
when('/products',controller: Ctrl}).
otherwise({redirectTo: '/index'})
}])
.run(function($rootScope,validateCookie) {
$rootScope.$on('$routeChangeSuccess',function () {
validateCookie($rootScope);
})
})
.factory('validateCookie',function($cookieStore,$http){
return function(scope) {
// Validate the cookie here...
}
})
如果您不需要在每次路由更改时运行,您可以更改“运行”功能:
.run(function($rootScope,validateCookie) {
validateCookie($rootScope);
})