简体   繁体   English

指令模板中的$ rootScope变量

[英]$rootScope variable in directive template

I am trying to access a variable from my $rootScope in a directives template. 我试图在指令模板中从我的$rootScope访问变量。 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 ? 如何访问变量$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). 虽然这有效,但我更喜欢Brad的解决方案(+1)。

Have you tried? 你有没有尝试过?

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

and in the HTML 并在HTML中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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