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.

Arif
  • 6,094
  • 4
  • 49
  • 81

3 Answers3

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])
felixmosh
  • 32,615
  • 9
  • 69
  • 88
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.

h01001000
  • 261
  • 8
  • 20
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? ).

Bassam
  • 831
  • 8
  • 17