Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch an object property?

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?

like image 922
CHS Avatar asked Mar 22 '23 03:03

CHS


1 Answers

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.

like image 124
Adam Avatar answered Mar 31 '23 19:03

Adam