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){
}
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With