2

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!

2 Answers 2

2

$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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! This doesn't exactly return the value of the changed property though.
2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.