[英]Can't access controller scope from directive
這是我的應用配置:
angular.module('myApp', ['myApp.directives', 'myApp.controllers', 'myApp.services']);
這是我的控制器:
angular.module('myApp.controllers', [])
.controller('MainCtrl', function ($scope) {
$scope.name = 'world';
});
這是我的指示:
var directives = angular.module('myApp.directives', []);
directives.directive("hello", function () {
return function (scope, elm, attrs) {
elm.text("hello, " + scope[attrs.name]);
};
});
這是我的HTML:
<div ng-controller="MainCtrl">
<h1 hello></h1>
</div>
問題是角度將指令渲染為:
你好,未定義
代替:
你好,世界
怎么了?
您正在訪問scope[attrs.name]
但該指令未提供屬性name
的值
有兩種選擇:
將指令更改為elm.text("hello, " + scope['name']);
這不是首選方法,因為它硬編碼到范圍屬性名稱
將html更改為<h1 hello name="name"></h1>
。 這是更好的,但我覺得它使用冗余屬性
我建議你將指令改為elm.text("hello, " + scope[attrs['hello']]);
甚至更好的elm.text("hello, " + scope.$eval(attrs['hello']));
這樣你也可以獲得表達式的好處(例如: <h1 hello="name|uppercase"></h1>
) 演示
這樣html就是<h1 hello="name"></h1>
關於attrs參數:它只不過是從dom元素上的屬性中獲取的字符串映射。
你可以做一些事情,在撰寫本文時,似乎沒有在Angular中記錄(參見Mark Rajcok在這里的評論: http ://docs.angularjs.org/api/ng.$rootScope.Scope)。
在你的指令中:
scope.$parent.name
如果在指令的scope
(在指令中)執行console.log(scope)
),您將看到這些屬性。
所有這些都說,我不知道這是否是“正確的”Angular慣例,因為這個都是無證件的,而且我還沒有找到關於如何訪問指令所在的控制器的任何其他更好的文檔內。
您可以使用scope
進行訪問。 看看http://jsfiddle.net/rPUM5/
directives.directive("hello", function () {
return function (scope, elm, attrs) {
elm.text("hello, " + scope.name);
};
});
我找到了另一個案例:
如果您正在訪問來自Ajax請求主體的變量,那么您必須等待直到設置變量 。
例如:
# in controller
$http.get('/preview').then( (response) ->
$scope.tabs = response.data.tabs
$scope.master_switch = '1'
console.info 'after get response in controller'
)
# in directive
directive('masterSwitch', ->
(scope, element, attrs) ->
alert 'in directive!' # will show before "after get response in controller"
console.info scope.master_switch # is undefined
setTimeout( -> console.info(scope.master_switch), 50) # => 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.