CHS
CHS

Reputation: 965

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?

Upvotes: 4

Views: 5771

Answers (2)

Elitward
Elitward

Reputation: 15

scope.$watchCollection (watchExpression, listener)

Refer to: https://docs.angularjs.org/guide/scope

Upvotes: 1

Adam
Adam

Reputation: 1143

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.

Upvotes: 6

Related Questions