[英]ng-controller variables are not visible in directive's link function
我正在嘗試讀取指令的鏈接函數中ng-controller函數內部初始化的變量。
HTML內容-index.html,
<div ng-controller="skCtrl">
<span sk-custom>click</span>
</div>
app.js,
app.controller('skCtrl', function ($scope, $element) {
$scope.data = "hello world"
})
app.directive("skCustom", function(){
return {
scope: {
data: "="
},
link: function(scope, elem, attr){
elem.bind("click", function(){
//both the statements throw error...
console.log(data)
console.log(scope.data)
})
}
}
})
當我單擊鼠標時,它將引發錯誤,
data is undefined
我在這里想念什么?
您正在使用綁定創建隔離范圍。 您可以刪除scope:{}
也可以通過指令設置綁定。
<sk-custom data="data"></sk-custom>
您也可以使用scope.$parent
,但是只有在絕對確定的情況下,才這樣做,因為它會建立對父范圍的依賴
您只需要指令中的數據即可,例如:
<span sk-custom data="name">click</span>
如在控制器中我定義的名稱:-
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
});
指令代碼:-
app.directive("skCustom", function(){
return {
scope: {
data: "="
},
link: function(scope, elem, attr){
elem.bind("click", function(){
//both the statements throw error...
console.log(scope.data)
})
}
}
});
數據未定義
發生這種情況是因為指令中未定義數據,而scope.data必須從指令模板傳遞。
PS:-scope。$ apply(); 如果您更改范圍以運行摘要周期,則必須使用。
綁定方法未達到摘要循環。 因此,您需要使用$ apply方法:
link: function(scope, elem, attr){
elem.bind("click", function(){
console.log(scope.data);
scope.$apply();
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.