mmmm
mmmm

Reputation: 3938

AngularJS run method doesn't always run

I'm writing simple app in Angular and I just wanted to check if user is logged in. If not - then redirect him. It almost works, but when I type in my browser [angularsite]#/home when I'm on #/form site, then I get the home page every second time, and every other second time I'm being redirected. Why run method does not run always? I was also checking with alert - and the same thing happens - alert shows up every second time. Here's my code:

angular.module('myLoginCheck',[]).factory('$logincheck', function(){
  return function(){
      // check if localstorage
  return false;  
  };
});

var myApp = angular.module('myApp',['ngRoute','myAppControllers','myLoginCheck']);

myApp.config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
    $routeProvider.
        when('/form',{
            templateUrl: 'views/form.html',
            controller: 'FormCtrl' 
        }).
        when('/home',{
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        }).
        otherwise({
        redirectTo: '/form'
        });
}]).run(function($logincheck,$location) {
    alert(2);
    if($logincheck())
    {

    }
    else
    {
        $location.path('/form');
    }
});

Upvotes: 0

Views: 130

Answers (1)

John Woodruff
John Woodruff

Reputation: 1666

The run function is for code which you intend to run once, at the initialization of the application. Anything you need to run every time you would want to put in a service or in the controller or whichever route you want to run it in.

Upvotes: 1

Related Questions