nikk wong
nikk wong

Reputation: 8670

AngularJS : $scope.$watch an object & return only its changed property

I'm doing some simple scope watching like:

$scope.$watch('myObject', function(newValue, oldValue) {
    if (newValue !== oldValue) {
       return newValue;
    }
}, true);

Where myObject is a normal object that has several properties. I would like to only return the property that changed, I.e, if there's a property which gets changed, like myObject.changedProperty, I would like to just return that.

Yet I want to watch the entire object (so, I don't have to set up different watches for each property). How can this be done?

Thank you!

Upvotes: 2

Views: 982

Answers (2)

nikk wong
nikk wong

Reputation: 8670

Thanks for the help everyone. I ended up doing something like this:

$scope.$watch('myObj', function(newValue, oldValue) {
    for (var prop in myObj) {
        if(newValue[prop] !== oldValue[prop]) {
           return newValue[prop];
        }
    }
}, true);

Upvotes: 2

wrongite
wrongite

Reputation: 918

$watchCollection does what you want. ($rootScope.Scope)

$watchCollection(obj, listener);

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.

The obj collection is observed via standard $watch operation and is examined on every call to $digest() to see if any items have been added, removed, or moved. The listener is called whenever anything within the obj has changed. Examples include adding, removing, and moving items belonging to an object or array.

Upvotes: 2

Related Questions