2

我正在使用 angular$resourceangular.copy允许用户重置表单。当用户单击保存按钮时,我调用$scope.save()$resource使用$save(). 在$save回调内部,我替换了 master 和 model,以反映后端所做的更改,同时这样做会导致$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);
   });
};
4

1 回答 1

2

这是因为您的观察者比较对象相等性而不是引用($scope.$watch方法中的第三个参数是true)。在内部 Angularangular.equals(newValue,oldValue)代替newValue === oldValue. 如果你这样做,var b = angular.copy(a)那么angular.equals(a,b)是真的(但是a === b假的)。

此外,当您执行 get$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
  });
};
于 2013-05-23T07:54:00.540 回答