在$ save回调中替换$ resource master / copy无法触发$ watch

时间:2013-05-23 07:13:09

标签: angularjs

我使用角度$resourceangular.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);
   });
};

1 个答案:

答案 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
  });
};