Angularjs $watchCollection发生了什么变化?

Angularjs $watchCollection发生了什么变化?,angularjs,Angularjs,使用$watchCollection检测已更改的密钥 newValue: Object {contentType: "217", audioType: 1, wordType: 209} oldValue: Object {contentType: "217", audioType: 1, wordType: 210} 通常一次只能更改一个键。我想检测哪一个,这样我就可以将更改保存到cookies中,而不必保存所有更改,即使它没有更改 谢谢 在您的情况下,您可以创建过滤器,以发现差异: a

使用
$watchCollection
检测已更改的密钥

newValue: Object {contentType: "217", audioType: 1, wordType: 209} 
oldValue: Object {contentType: "217", audioType: 1, wordType: 210} 
通常一次只能更改一个键。我想检测哪一个,这样我就可以将更改保存到cookies中,而不必保存所有更改,即使它没有更改


谢谢

在您的情况下,您可以创建
过滤器
,以发现差异:

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

积分到

此处不需要
$watchCollection

只需使用
$watch
,第三个参数为
true

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