I want to have an attribute directive that can be used like this:
<div my-dir="{items:m.items, type:'0'}"></div>
In my directive I can turn this into an object like:
function (scope, element, attributes, modelController)
{
var ops = $.extend({}, scope.$eval(attributes.myDir));
}
Now say m.items is an array. And somewhere down the line an ajax call replaces the array with a new one. I'd like to watch for this.
How can I watch m.items
or whatever was typed in for the items property in the attribute? What should the watch expression be?
You should be able to use scope.$watch to watch the attribute. Angular will invoke the callback with the entire object when any of the values change.
function(scope, elem, attrs) {
scope.$watch(attrs.myDir, function(val) {
// Do something with the new value, val.
}, true);
}
http://plnkr.co/edit/JBGqW8uFzh1eJ1Ppq3fT
Anytime the model changes (by typing something in the input) the directive updates the elements html in the $watch.
Edited my answer: you want to include true as the last argument to compare object values, not references. Otherwise you will run digest more than 10 times and get an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With