使用$watchCollection
检测更改的密钥
newValue: Object {contentType: "217", audioType: 1, wordType: 209}
oldValue: Object {contentType: "217", audioType: 1, wordType: 210}
通常一次只会改变一个键。我想检测哪一个,以便我可以将更改保存到cookie中,而不是必须保存所有这些,即使它没有改变。
谢谢!
答案 0 :(得分:2)
你在这里不需要$watchCollection
。
只需将$watch
与第三个参数一起用作true
。
答案 1 :(得分:1)
在您的情况下,您可以创建可以找到差异的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?
的信用