更好的解决方案可以是该功能;
$scope.equalsAdvanced=function (sourceObject, targetObject, ignoredProperties)
{
// direct compare if there is no ignored properties
if (!ignoredProperties || (angular.isArray(ignoredProperties) && ignoredProperties.length<=0)) {
return angular.equals(sourceObject, targetObject);
}
// take the original ignored property list to a new variable
var ignoredPropertyList=ignoredProperties;
// make it array if it is not
if (!angular.isArray(ignoredPropertyList)) {
var list = [];
list.push(ignoredPropertyList);
ignoredPropertyList = list;
}
// compare property list
for (propertyName in sourceObject) {
if (ignoredPropertyList.indexOf(propertyName) >= 0)
continue;
var sourceValue = sourceObject[propertyName];
var targeValue = targetObject[propertyName];
if (!angular.equals(sourceValue, targeValue))
return false;
}
return true;
};
您可以查看小提琴上的示例代码:http:
//jsfiddle.net/tursoft/DpEwV/4/
这可能比以前更好;
代码:
// service
myApp
.service("utils", function()
{
self=this;
// watchAdvanced =====================
self.$watchAdvanced = function ($scope, exp, ignoredProperties, callback)
{
$scope.$watch(exp, function (newValue, oldValue) {
if (self.equalsAdvanced(newValue, oldValue, ignoredProperties))
return;
callback(newValue, oldValue);
}, true);
}
// equalsAdvanced =====================
self.equalsAdvanced=function (sourceObject, targetObject, ignoredProperties)
{
// direct compare if there is no ignored properties
if (!ignoredProperties || (angular.isArray(ignoredProperties) && ignoredProperties.length<=0)) {
return angular.equals(sourceObject, targetObject);
}
// take the original ignored property list to a new variable
var ignoredPropertyList=ignoredProperties;
// make it array if it is not
if (!angular.isArray(ignoredPropertyList)) {
var list = [];
list.push(ignoredPropertyList);
ignoredPropertyList = list;
}
// compare property list
for (propertyName in sourceObject) {
if (ignoredPropertyList.indexOf(propertyName) >= 0)
continue;
var sourceValue = sourceObject[propertyName];
var targeValue = targetObject[propertyName];
if (!angular.equals(sourceValue, targeValue))
return false;
}
return true;
};
});
用法:
utils.$watchAdvanced($scope, "user", ["_State", "ID"], function(newValue, oldValue)
{
$scope.changeCount+=1;
$scope.logs.push($scope.changeCount + ": User object is changed!");
}, true);
小提琴的源代码:http:
//jsfiddle.net/tursoft/5rLfr/2/