简体   繁体   中英

$rootScope variable in directive template

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 ?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM