[英]$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.