繁体   English   中英

指令模板中的$ rootScope变量

[英]$rootScope variable in directive template

我试图在指令模板中从我的$rootScope访问变量。 但是,我无法访问它。

简化模板:

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

指令:

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

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

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

如何访问变量$rootScope.serverRoot

您已为您的指令定义了新范围

scope: {
    item: '='
},

所以它不会是你的链接 - >范围或控制器 - >范围的一部分。 您应该可以通过它访问它

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

此外,您的实际指令声明需要看起来像

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

尝试:

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

虽然这有效,但我更喜欢Brad的解决方案(+1)。

你有没有尝试过?

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

并在HTML中

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

暂无
暂无

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

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