1

Using $watchCollection to detect the changed key

newValue: Object {contentType: "217", audioType: 1, wordType: 209} 
oldValue: Object {contentType: "217", audioType: 1, wordType: 210} 

Usually only one key will change at a time. I'd like to detect which one so I can save that change to the cookies rather than having to save all of them even if it didn't change.

Thanks!

Mohamed El Mahallawy
  • 13,024
  • 13
  • 52
  • 84

2 Answers2

2

You don't need $watchCollection here.

Just use $watch with 3rd parameter as true.

Miraage
  • 3,334
  • 3
  • 26
  • 43
1

In your case you can create filter that would find difference:

app.filter('diff', function () {
  return function (objectA, objectB) {
    var propertyChanges = [];
     var objectGraphPath = ["this"];
     (function(a, b) {
        if(a.constructor == Array) {
           // BIG assumptions here: That both arrays are same length, that
           // the members of those arrays are _essentially_ the same, and 
           // that those array members are in the same order...
           for(var i = 0; i < a.length; i++) {
              objectGraphPath.push("[" + i.toString() + "]");
              arguments.callee(a[i], b[i]);
              objectGraphPath.pop();
           }
        } else if(a.constructor == Object || (a.constructor != Number && 
                  a.constructor != String && a.constructor != Date && 
                  a.constructor != RegExp && a.constructor != Function &&
                  a.constructor != Boolean)) {
           // we can safely assume that the objects have the 
           // same property lists, else why compare them?
           for(var property in a) {
              objectGraphPath.push(("." + property));
              if(a[property].constructor != Function) {
                 arguments.callee(a[property], b[property]);
              }
              objectGraphPath.pop();
           }
        } else if(a.constructor != Function) { // filter out functions
           if(a != b) {
              propertyChanges.push({ "Property": objectGraphPath.join(""), "ObjectA": a, "ObjectB": b });
           }
        }
     })(objectA, objectB);
     return propertyChanges;
  }
});

And then use it in your $watchCollection:

var diff = $filter('diff')(newValue, oldValue);

Credits to How can I get a list of the differences between two JavaScript object graphs?

Community
  • 1
  • 1
dubadub
  • 3,312
  • 3
  • 23
  • 28