admin管理员组

文章数量:1301510

I am trying to access a variable from my $rootScope in a directives template. However, I can't access it.

The simplified template:

<div class="item">
    {{ serverRoot }}
</div>

And the directive:

ItemModule.directive('item', [function ($rootScope) {
    return {
        restrict: 'E',
        scope: {
            item: '='
        },

        templateUrl: 'js/modules/items/directives/templates/item.html',

        link: function (scope, iElement, iAttrs) {
        }
    };
}])

How can I access the variable $rootScope.serverRoot?

I am trying to access a variable from my $rootScope in a directives template. However, I can't access it.

The simplified template:

<div class="item">
    {{ serverRoot }}
</div>

And the directive:

ItemModule.directive('item', [function ($rootScope) {
    return {
        restrict: 'E',
        scope: {
            item: '='
        },

        templateUrl: 'js/modules/items/directives/templates/item.html',

        link: function (scope, iElement, iAttrs) {
        }
    };
}])

How can I access the variable $rootScope.serverRoot?

Share asked Jun 19, 2014 at 14:53 MaehMaeh 1,7644 gold badges18 silver badges31 bronze badges 1
  • btw rather define ItemModule.directive('item', ['$rootscope', function ($rootScope) {, or use a grunt task to avoid issues when minifying javascript. – Braulio Commented Jun 19, 2014 at 15:01
Add a ment  | 

3 Answers 3

Reset to default 8

You have defined a new scope for your directive with

scope: {
    item: '='
},

So it won't be part of your link -> scope or controller -> scope. You should be able to access it via

link: function (scope, iElement, iAttrs) {
    scope.serverRoot = $rootScope.serverRoot;    
}

Further, your actual directive declaration needs to look like

ItemModule.directive('item', [ '$rootScope', function ($rootScope) {

Try:

<div class="item">
    {{ $parent.myServerRoot }}
</div> 

Although this works, I prefer Brad's solution (+1).

Have you tried?

link: function (scope, iElement, iAttrs) {
  scope.myServerRoot = $rootScope.serverRoot;
}

and in the HTML

<div class="item">
    {{ myServerRoot }}
</div>

本文标签: javascriptrootScope variable in directive templateStack Overflow