1

I'm trying to check if a user has a specific role from my component's template.

For example, this could be my session service :

function Session() {
    'ngInject';

    var userRoles = {};

        ...

    function hasRole(role) {
        if(userRoles[role]) {
            return true;
        }
        else {
            return false;
        }
    };

    return {
      getUserRoles: getUserRoles,
      setUserRoles: setUserRoles,
      hasRole: hasRole
    };
};

I'll then assin my service to the $rootScope in my .run() method :

$rootScope.session = Session;

But it seems that I cannot access my session service from my component's template :

<div ng-show="session.hasRole('TEST')">
   Hi, {{session.getUserRoles() | json}}
</div>

It only works when I specify the $root service :

<div ng-show="$root.session.hasRole('TEST')">
   Hi, {{$root.session.getUserRoles() | json}}
</div>

Why is that ? And how can I avoid using $root, to access my $rootScope's services when using angular's component architecture ?

redAce
  • 1,558
  • 4
  • 14
  • 24
  • A component's scope (in contrast to directives) is always isolate, you cannot use it, and you shouldn't. Why do you want to avoid using `$root` anyway? – user1238367 Jan 15 '17 at 16:48
  • Use a service instead of `$rootScope`. Assign value to that service in run block – charlietfl Jan 15 '17 at 18:11
  • @user1238367 I would be using it in all my views. And since I've read that it is considered to be bad practice,I thought I would ask for a better alternative. charlietfl, I'll have to pass it to every single one of my controllers and that's what I'm trying to avoid in the first place. – redAce Jan 15 '17 at 18:15

0 Answers0