user1765862 user1765862 - 5 months ago 34
AngularJS Question

securing access to url and rootScope undefined

(function () {
"use strict";
var app = angular.module("myApp",
["common.services",
"$rootScope",
"ui.router",
"ui.mask",
"userService",
"ui.bootstrap"]);

app.config(["$stateProvider", "$urlRouterProvider","$rootScope",
function ($stateProvider, $urlRouterProvider, $rootScope) {
$urlRouterProvider.otherwise("/");

$stateProvider
.state("index", {
url: "/",
templateUrl: "app/index.html",
})
// Home page /* SECURED */
.state("home", {
url: "/home",
templateUrl: "app/home/home.html",
controller: "HomeController as vm",
data: {
requiresLogin: true
}
})
// Login
.state("login", {
url: "/login",
templateUrl: "app/login/login.html",
controller: "LoginController as vm"
})

}]
);
$rootScope.$on('$stateChangeStart', function (e, to, userService) {
if (to.data && to.data.requiresLogin) {
if (!userService.user.loggedIn()) {
//token not found/not valid
e.preventDefault();
$location.path('/login');
}
}
});
}());

Answer

You didn't post what the problem is, but I assume it is that nothing works. If so here is obvious problem with your code: you are trying use $rootScope as module dependency to application module.

Correct module definition must be:

angular.module("myApp", [
     "common.services",
     "ui.router",
     "ui.mask",
     "userService",          
     "ui.bootstrap"
])

I removed "$rootScope" from the list.

UPD. Closer look revealed another problem. You can't inject $rootScope into config block. Move it to the run:

app
  .config([...])
  .run(['$rootScope', function($rootScope) {
    $rootScope.$on(...);
  }];