指令模板中的$ rootScope变量

时间:2014-06-19 14:53:44

标签: javascript angularjs

我正在尝试从指令模板中的$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

3 个答案:

答案 0 :(得分:8)

您已使用

为指令定义了新范围
scope: {
    item: '='
},

因此它不会成为您链接的一部分 - &gt;范围或控制器 - &gt;范围。您应该可以通过

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

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

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

答案 1 :(得分:1)

尝试:

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

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

答案 2 :(得分:0)

你试过吗?

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

并在HTML中

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