Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function in every page in AngularJs

I have created a function that validates if a Cookie exists and I want to run this function in every page using angularjs. I just can't seem to make the function run. Should I put it the module on in a new controller?

This is how far I reached:

  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){


}
like image 307
Vitaliy.sikor Avatar asked Apr 22 '13 15:04

Vitaliy.sikor


1 Answers

I think there would be a couple ways of solving this. If you want to cause this validation to happen every time you change routes (which means it will run when the application first starts as well as on every page that you go to within the application), you could do something like this:

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...
    }
})

If you don't need to run on every route change, you could just change the "run" function:

.run(function($rootScope, validateCookie) {
    validateCookie($rootScope);
})
like image 174
Jason Aden Avatar answered Oct 14 '22 06:10

Jason Aden