Arif Arif -3 years ago 96
AngularJS Question

How to know the changed property of an object using angularJS

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.

Answer Source

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])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download