2

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');
    });
2
  • show your code where you have declared the utilisateur on $rootScope Commented Feb 23, 2015 at 22:12
  • It looks like $rootScope is working but utilisateur is not defined yet. Commented Feb 23, 2015 at 22:12

4 Answers 4

1

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

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

3 Comments

hi; can you please tell me how I can do such: I want to use the same URL (/home) but have different views according to the user role (for example if his role is admin I redirect him to the admin page, else I redirect him to the main page, but the two pages shoud have the same route (/home).
I think the ideal solution would be to have 2 separate routes: - /admin/home - /home I'm assuming that you know if the user is an admin or not, only after your angular module starts up, so you won't be able to modify the $routeProvider inside of the config block. If having the 2 separate routes is not an option, you could do a check inside of your 'homeCtrl', for isAdmin or not. And in your view, have 2 div blocks. <div ng-if="isAdmin()"></div> <div ng-if="!isAdmin()"></div>
Editted my answer above to include possible options from my previous comment.
0

Your problem seems like you have two different views, and on condition base you have to redirect views.

Pass the parameters in url like from your views (Create/Edit link etc.) As i have set the cookie on login and accessed here as a parameters or you can use different way to access the parameters.

'<a href="#/editTest/{{model._id}}/' + getCookie(escape('cformview'))+ '" title="Edit Test"></a>'

And your config in $routeProvider use like this:

   $routeProvider.when("/editTest/:ID/:flagTab",
                        {                               
                             templateUrl: function (params) {
                                var flag = params.flagTab;                                    
                                if (flag == 'tabPanelView') {
                                    return '/apps/templates/editTest.html';
                                }
                                else {
                                    return '/apps/templates/editTestPageView.html';
                                }                                    
                            },
                            controller: 'EditTestController'
                        });.

Refere a link swtiching views in routeProvider based on condition

Comments

0

Instead of describing different ways to achieve what you would like to, the code snippet below answers the actual question that was asked:

How can I access a variable defined with $rootScope in a templateUrl function?

The answers above and here imply there is no way to reference $rootScope within the config/$routeProvider. While that may strictly be true, there is a simple way to access the $rootScope through $routeProvider. Below is how to do this:

Sample HTML:

<div ng-app="myApp">
  <div ng-controller="masterController">
      <script type="text/ng-template" id="home.html">{{something}}</script>
      <a href="#page">Page</a>
      <div ng-view></div>
  </div>
</div>

Sample javascript:

var myApp = angular.module('myApp',[],function($routeProvider) {        

$routeProvider
    .when('/home',{templateUrl:'home.html'})
    .when('/page',
    {
      template:'<p>{{something}}</p>', 
      controller:'masterCtrlWrapper'
    })
    .otherwise({redirectTo:'/home'});
});

myApp.controller('masterCtrlWrapper', function($rootScope)
{   $rootScope.changeVariable(); }); 

myApp.controller('masterController', function($rootScope)
{
  $rootScope.something = 'This is the $rootScope talking.'
  $rootScope.pressCount = 0;
  $rootScope.changeVariable = function()
  { $rootScope.something = "This function was run " + $rootScope.pressCount++ + " times."; };
});

Comments

0

Like others have said, $rootScope doesn't exist yet, but unlike their answers, it doesn't at all mean you can't use it at all, you just have to code-in the wait.

Here is your example working but just printing since we dont have the templates.

myApp

.provide('home', function() {
    var $rootScope = null;

    this.templateUrl = function() {
        var check =
            $rootScope.utilisateur &&
            $rootScope.utilisateur.user.role_id
        ;

        console.log(check);
        return (check) ? 'partials/home.html' : 'partials/login.html';
    };
    this.controller = 'homeCtrl';
    this.resolve = {load:['$rootScope', function(fetched) { $rootScope = fetched; }]};

    this.$get = function() { };
})

.config(['$routeProvider', 'homeProvider', function($routeProvider, homeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'partials/login.html',
            controller  : 'loginCtrl'
        })
        .when('/home', homeProvider)
        .otherwise({redirectTo:'/'})
    ;
}])

;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.