我试图在指令模板中访问我的$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 ->作用域或controller ->作用域的一部分。你应该可以通过
访问它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>