Reputation: 1406
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.
Upvotes: 16
Views: 22136
Reputation: 328
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
}
}
}
};
});
You can use $watch that is also correct.
Upvotes: 4
Reputation: 133
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);
});
}
} ;
}
);
Upvotes: -2
Reputation: 5237
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);
});
}
}
}
};
});
Upvotes: 6
Reputation: 16498
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);
});
}
} ;
}
);
Upvotes: 22