美元的范围.$watch完整的形式,但旧价值只有一次

$scope.$watch whole form, but get old value only once

本文关键字:一次 watch 范围 美元      更新时间:2023-09-26

我想使用$scope。$watch监视我的整个表单输入并检测更改,然后显示警报"数据已更改"。请保存"。问题是,我想传递oldValue只有当数据是从服务器获得。

$http({
        method: "post",
        url: "url",
        data: {
            Pages: {
                id: pageId
            }
        },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    }).success(function(data) {
        $scope.data = data.editedPage.jkOutputContainer.editedPage.pagesObject;
        $scope.$watch('data',function(newValue, oldValue) {
            if(newValue != oldValue) {
                $scope.dataHasChanged = true;
            } else {
                $scope.dataHasChanged = false;
            }
        }, true);
    });

我可以在我的表单中使用ng-init和ng-change对每个输入,但我想使用$范围。注意表格。

编辑:简而言之,我想隐藏警报当用户返回他的更改状态,它是从服务器得到的

$scope.watch('[formname]', checkChanged, true)
function checkChanged(newVal) {
    if (!angular.equals(newVal,$scope.data)) warnUser()
}

^这将监视表单中的每个表达式并警告用户

要解决您的问题,不要将服务器的响应绑定到$scope变量,而只需将其分配给脚本中引用的变量。下面是一个例子。

$http({
  method: "post",
  url: "url",
  data: {
      Pages: {
          id: pageId
      }
  },
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data) {
  // To solve your problem, just store the server data in a variable.
  var fromServer = data.editedPage.jkOutputContainer.editedPage.pagesObject;
  $scope.data = fromServer; //<- Reference the var here.
  $scope.$watch('data',function(newValue, oldValue) {
      if(newValue != fromServer) { //<- Reference the var here.
          $scope.dataHasChanged = true;
      } else {
          $scope.dataHasChanged = false;
      }
  }, true);
});

希望这对你有帮助!