【问题标题】:$watchCollection what has changed?$watchCollection 发生了什么变化?
【发布时间】:2014-06-27 00:32:44
【问题描述】:

使用$watchCollection 检测更改的密钥

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

通常一次只更改一个键。我想检测是哪一个,这样我就可以将更改保存到 cookie 中,而不必保存所有这些更改,即使它没有更改。

谢谢!

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    这里不需要$watchCollection

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

    【讨论】:

      【解决方案2】:

      在您的情况下,您可以创建 filter 来发现差异:

      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中使用它:

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

      感谢How can I get a list of the differences between two JavaScript object graphs?

      【讨论】:

        猜你喜欢
        • 2015-09-25
        • 2019-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-26
        • 2020-07-19
        • 2016-02-26
        • 2018-12-24
        相关资源
        最近更新 更多