我正试图找出在指令中更新模型时如何收听。
eventEditor.directive('myAmount',function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
scope.$watch(attr['ngModel'], function (v) {
console.log('value changed, new value is: ' + v);
});
}
}
}
};
});
该指令在ng-repeat中被调用为
<div ng-repeat="ticket in tickets">
<input my-amount ng-model="ticket.price"></input>
</div>
非常乐意为您提供帮助。我不明白范围属性在ng-repeat中是怎么样的。
感谢。
答案 0 :(得分:19)
http://jsbin.com/mihupo/1/edit
attrs
代替attr
app.directive('myAmount',function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
scope.$watch(attrs['ngModel'], function (v) {
console.log('value changed, new value is: ' + v);
});
}
} ;
}
);
答案 1 :(得分:5)
尝试这样做
eventEditor.directive('myAmount',function(){
return {
restrict: 'A',
scope: {model: '=ngModel'},
link: function(scope, elem, attrs) {
scope.$watch('model', function (v) {
console.log('value changed, new value is: ' + v);
});
}
}
}
};
});
答案 2 :(得分:2)
eventEditor.directive('myAmount',function(){
return {
restrict: 'A',
required : 'ngModel' // Add required property
link: function(scope, elem, attrs,ngModelCtr) {
ngModelCtr.$render = function(){ // Add $render
// Your logic
}
}
}
};
});
您可以使用也是正确的$ watch。
答案 3 :(得分:-1)
以下代码适用于我。
app.directive('myAmount',function(){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
attrs.$observe('ngModel', function (v) {
console.log('value changed, new value is: ' + v);
});
}
} ;
}
);