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

标签 angularjs

我使用 Angular $resourceangular.copy 来允许用户重置表单。当用户单击保存按钮时,我调用 $scope.save() 并使用 $save() 保存 $resource。在 $save 回调中,我替换了 master 和模型,以反射(reflect)在后端所做的更改,同时 $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);
   });
};

最佳答案

这是因为您的观察程序比较的是对象相等性而不是引用($scope.$watch 方法中的第三个参数是 true)。 Angular 内部执行的是 angular.equals(newValue,oldValue) 而不是 newValue === oldValue。如果您执行 var b = angular.copy(a)angular.equals(a,b) 为 true(但 a === b > 是假的)。

此外,当您执行 $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
  });
};

关于angularjs - 在 $save 回调中替换 $resource master/copy 无法触发 $watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16707757/

相关文章:

AngularJS/ Material : why the expression is not evaluated?

javascript - AngularJS 将对象添加到数组会更新所有相似的对象

angularjs - angular $http 服务中,返回

javascript - 在 AngularJS 中折叠/展开表单字段

javascript - 按自定义顺序对对象数组进行排序

javascript - AngularJS 提交表单

html - AngularJS - 如何清除 ui-select 多个选项输入中的查询文本

javascript - Angular 模型失去了 ng-included 在指令中的范围

javascript - 使用 PHP 实时托管 MySQL 无法连接到我的 AngularJS

angularjs - 在这个测试用例中,当增加一个简单的计数器时,是什么导致 react 比 Angular 慢得多?