Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
88
rated 0 times [  94] [ 6]  / answers: 1 / hits: 15693  / 11 Years ago, tue, october 29, 2013, 12:00:00

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


More From » angularjs

 Answers
7

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



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


[#74630] Tuesday, October 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jalyn

Total Points: 173
Total Questions: 96
Total Answers: 90

Location: Somalia
Member since Mon, Feb 27, 2023
1 Year ago
;