Search code examples
angularjsangularjs-scope

using $rootScope in templateUrl function


I just started with angularJS and I have a question: How can I access a variable defined with $rootScope in a templateUrl function? Here is my code:

myApp.config(['$routeProvider',
            function($routeProvider, $rootScope) {
              $routeProvider.
                when( '/', {
                  templateUrl: 'partials/login.html',
                  controller: 'loginCtrl'
                }).
                when( '/home', {
                  templateUrl: function($rootScope){
                      console.log($rootScope.utilisateur.user.role_id);
                      if ($rootScope.utilisateur.user.role_id==2){
                      return  'partials/home.html';
                      }
                      else return 'partials/login.html';
                  },
                  controller: 'homeCtrl'
                }).
                otherwise({redirectTo:'/'});
            }]);

It tells me that utilisateur is undefined.

I defined it in the index controller:

$rootScope.utilisateur = null;
$rootScope.rapports = null;

And then in the LoginCtrl:

 var user = Authentification.login(email,password);
    user.success(function(response){
        $rootScope.utilisateur = response;
        console.log($rootScope.utilisateur);
        $location.path('/home');
    });

Solution

  • You cannot use the $rootScope inside of the config block, as the config block runs before the $rootScope is created. Constants and providers may be used inside of the config block instead. If constants are not an option for you, you may want to redirect to the correct url inside of your homeCtrl.

    [EDIT] Added possible solution from comment below:

    Option 1: Have 2 different routes

    • /admin/home
    • /home

    Option 2: Switch templates according to permission inside of controller/view

    home.html

    <div ng-switch="utilisateur.user.role_id">
        <div ng-switch-when="2">
        <!-- is admin -->
        </div>
        <div ng-switch-default>
        <!-- not admin -->
        </div>
    </div>
    

    Not the ideal solution, but it'd work for what you are trying to do, based on your comments below