如何在AngularJs中的每个页面中运行一个函数

Vit*_*kor 12 cookies jquery module angularjs

我创建了一个函数来验证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){


}
Run Code Online (Sandbox Code Playgroud)

Jas*_*den 37

我认为有几种方法可以解决这个问题.如果您希望每次更改路由时都发生此验证(这意味着它将在应用程序首次启动时以及在您在应用程序中的每个页面上运行),您可以执行以下操作:

angular.module('myApp', ['ngCookies']).
config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/index', {templateUrl: '/tmpl/index.html', controller: IndexCtrl}).
        when('/products', {templateUrl: '/tmpl/products.html', 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 Code Online (Sandbox Code Playgroud)

如果您不需要在每次路由更改时运行,您只需更改"运行"功能:

.run(function($rootScope, validateCookie) {
    validateCookie($rootScope);
})
Run Code Online (Sandbox Code Playgroud)