我使用角度$resource
和angular.copy
来允许用户重置表单。当用户点击保存按钮时,我会拨打$scope.save()
并使用$resource
保存$save()
。在$save
回调中,我替换了主服务器和模型,以反映在后端上所做的更改,同时$watch
无法获取更改,直到用户手动编辑表单。
任何想法为什么?
// db.schema is a $resource
var master = db.schema.get(function() {
$scope.schema = angular.copy(master);
});
$scope.$watch('schema', function() {
// triggers when $scope.schema is changed
}, true);
$scope.save = function() {
$scope.schema.$save(function(savedSchema) {
master = new db.schema(savedSchema);
// this won't trigger the $watch, but editing the form will
$scope.schema = angular.copy(master);
});
};
答案 0 :(得分:2)
这是因为您的观察者比较对象相等而不是引用($scope.$watch
方法中的第三个参数是true
)。内部Angular执行angular.equals(newValue,oldValue)
而不是newValue === oldValue
。如果您执行var b = angular.copy(a)
,则angular.equals(a,b)
为真(但a === b
为false)。
此外,当您执行$scope.schema.$save
$scope.schema
的值被服务器的响应取代时 - 我试图解释发生了什么:
$scope.save = function() {
$scope.schema.$save(function(savedSchema) {
// $scope.schema === savedSchema is now true
// if you don't want this behavior you could do db.schema.save({},$scope.schema ... instead
// if the request body equals the response body the watcher will not get called,
master = new db.schema(savedSchema);
// master is now a copy of savedSchema
// angular.equal(savedSchema, master) is true
// savedSchema === master is false
// this won't trigger the $watch, but editing the form will
$scope.schema = angular.copy(master);
// $scope.schema is now a copy of a copy of itself...
// $scope.schema === savedSchema is now false
// angular.equal(savedSchema,$scope.schema) is true
});
};