[英]Why is the directive not executed
我想知道為什么我單擊項目后沒有執行指令my-dir
。 它在頁面加載和完成編輯事件時執行(事實上,子div表示ng-grid
單元格,這就是為什么存在這樣的事件)
<div ng-controller="Cntl">
<div ng-click="select(item1)" my-directive="item1"></div>
<div ng-click="select(item2)" my-directive="item2"></div>
<div ng-click="select(item3)" my-directive="item3"></div>
</div>
Controller和指令大致定義如下:
app.controller('Cntl',function($scope, ...){
$scope.highlightedItems = {item1:true, item2:false, item3:false};
$scope.select = function(item){
// basically set the value of the property in $scope.highlightedItems to true
// the structure of the items is a bit more sophisticated though
// but it doesnt matter here
};
$scope.is_highlighted = function(item){ // checks if $scope.highlightedItems is true or false for item
};
};
app.directive('myDirective', function(){
return {
link: function(scope, element, attr){
if(scope.is_highlighted(attr.myDirective)){
// do something
}
};
};
});
提前致謝! (注意,我只為這個問題編寫了代碼,它是原始的模型,但它希望能說明我的問題)
指令中的link
函數只調用一次(當范圍鏈接到DOM時)。 這是在鏈接階段。
所以條款:
if(scope.is_highlighted(attr.myDirective)){
// do something
}
目前只能按指令執行一次。
如果要監視值的更改,則需要在指令中進行設置:
link: function(scope, element, attr){
scope.$watch('highlightedItems', function(value) {
if(scope.is_highlighted(attr.myDirective)){
// do something
}
}, true);
};
由於Davin Tryon已經提到link
只執行一次,你要么必須附加$watch
/ $watchCollection
或附加一個點擊處理程序來處理更改
app.directive('myDirective', function () {
return {
link: function (scope, element, attr) {
var listener = function () {
if (scope.is_highlighted(attr.myDirective)) {
// do something
}
};
listener();
element.on('click', listener);
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.