Reputation: 6129
I want to watch a model from inside a directive that I place as an attribute on an input
element:
<input id="mymodel_headline" name="mymodel[headline]"
ng-model="mymodel.headline" sps-watch="true" type="text">
If I'm reading the docs right I should be able to get the value either through the link function's attrs
parameter, or from requiring ngModel
. However, neither of these approaches are working:
app.directive('spsWatch', function() {
return {
require: "ngModel",
link: function(scope, element, attrs, ngModel) {
console.log("directive called");
console.log(attrs.ngModel);
scope.$watch(scope[attrs.ngModel], function(result) {
console.log("watching via attribute");
console.log(result);
});
scope.$watch(ngModel, function(result) {
console.log("watching via ngModel");
console.log(result)
});
}
};
});
They seem to run once only, when the directive is first created.
Upvotes: 1
Views: 120
Reputation: 1176
You can retrieve the value of your model via ngModel.$viewValue
. Return that from an anonymous function in your $watch
expression, and changes in the model will trigger your $watch
function:
scope.$watch(function () {
return ngModel.$viewValue;
}, function(result) {
console.log("watching via ngModel");
console.log(result)
});
Upvotes: 1