0
app.controller('indexController', ['$scope', 'authService', function ($scope, authService) {

    var vm = this;

    vm.$onInit = function () {
        vm.active = {
            "home": true,
            "welcome": false,
            "user": false,
            "logout": false,
            "login": false,
            "signup":false
        };
    };

    $scope.$watch('vm.active', function (newObj, oldObj) {
        // How to detect which property has changed ?
    }, true);

}]);

This way i tried, but i don't know how can i detect in watch(shown in my example code), which property has changed.

3
  • You want an object differ? Commented Aug 15, 2017 at 19:47
  • @DaveNewton Yes. Say, if i make user = true then i want "user" property. Commented Aug 15, 2017 at 19:50
  • Why do you need to know which one? Commented Aug 15, 2017 at 20:01

3 Answers 3

2

You can run on the keys of one of the object, and filter it by the value. Something like that:

const obj1 ={
    "home": true,
    "welcome": false,
    "user": false,
    "logout": false,
    "login": false,
    "signup":false
};

const obj2 = {
    "home": true,
    "welcome": false,
    "user": false,
    "logout": true,
    "login": true,
    "signup":false
};

const diff = Object.keys(obj1).filter((key) => obj1[key] !== obj2[key])
Sign up to request clarification or add additional context in comments.

Comments

0

i think watcher can't detect and property that's changed , you can make trick solution by using watchGroup or watchCollection ( see $watchCollection will shallow watch the properties on a single object and notify you if one of them changes.

$watchGroup however watches a group of individual watch expressions.)

also you can check ( how to know which object property changed? ).

Comments

0

const obj1 ={
    "home": true,
    "welcome": false,
    "user": false,
    "logout": false,
    "login": false,
    "signup":false
};

const obj2 = {
    "home": true,
    "welcome": false,
    "user": false,
    "logout": true,
    "login": true,
    "signup":false,
    "somethingNew": false
};


for (myProperty in obj2){
    if (obj2[myProperty] !== obj1[myProperty]){
        alert(myProperty + ' has changed!');
    }
}

I believe this should do the trick using a for...in loop.

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.