1

I'm trying to configure my route in such a way to redirect to the login page if user is not logged. This is my code:

angular.module('witBiz.services', []);
angular.module('witBiz.controllers', ['witBiz.services']);
var witBizModule = angular.module('witBiz', ['ngRoute' , 'witBiz.controllers', 'witBiz.services'   ]);

witBizModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/login', {templateUrl: 'resources/views/login.html', controller: 'LoginController'});
    $routeProvider.when('/index', {templateUrl: 'resources/views/index.html', controller: 'IndexController'});
    $routeProvider.otherwise({redirectTo: 'resources/views/index.html'});
}])
    .run(['$rootScope',  'checkLogin', function($rootScope, checkLogin ,$routeProvider ) {
        $rootScope.$on('$routeChangeSuccess', function () {
           if (checkLogin())
                $location.url("/index");
        })
    }])
    .factory('checkLogin', function(){
        return function() {
            //perform real logic here
            return true;
        }
    })

where basically I declare modules and services. Now the problem is $location is not defined so I get error. I tried to inject $location as dependency like this but I got undefined injection (injpt):

.run(['$rootScope',  'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
        $rootScope.$on('$routeChangeSuccess', function () {
           if (checkLogin())
                $location.url("/ciao");
        })
    }])

So I'm wondering how I can use the builtin $location services inside my "run" method...why can I inject it as a dependency as $rootScope or checkLogin?!

I'm using angular 1.2.0 rc2.

Thanks

1 Answer 1

2

Here is a working example http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview

Couldn't reproduce the error with $location not working inside .run

Sign up to request clarification or add additional context in comments.

2 Comments

I have been struggling with understanding app.run your example helped
This feels kludgy, but it worked, so after two days of struggle - I will accept it as a working answer. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.