Dario
Dario

Reputation: 6280

Angular JS: $location injection undefined

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

Upvotes: 1

Views: 15629

Answers (1)

bekite
bekite

Reputation: 3444

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

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

Upvotes: 2

Related Questions