问题
I'm trying to find out how I can listen to when the model is updated within an directive.
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);
});
}
}
}
};
});
The directive is called within ng-repeat as
<div ng-repeat="ticket in tickets">
<input my-amount ng-model="ticket.price"></input>
</div>
Very happy for any help. I don't understand how the scope attribute looks like within an ng-repeat.
Thanks.
回答1:
http://jsbin.com/mihupo/1/edit
attrs
instead 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);
});
}
} ;
}
);
回答2:
Try doing this
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);
});
}
}
}
};
});
回答3:
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
}
}
}
};
});
- Add a required property with ngModel, Since you are using ngModel (i mean actual angular ng-model, not the user custom ng-model attribute).
- Then call $render function. It will execute as soon as there is a change in ngModel (change in values of $modelValue and $viewValue). https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$render
You can use $watch that is also correct.
回答4:
Following code works for me.
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);
});
}
} ;
}
);
来源:https://stackoverflow.com/questions/25878189/angularjs-listen-to-model-change-in-a-directive