【问题标题】:$scope.$watch whole form, but get old value only once$scope.$watch 整个表单,但只获取一次旧值
【发布时间】:2015-08-06 15:05:31
【问题描述】:

我想在我的整个表单输入中使用 $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。

编辑:简而言之,当用户将更改返回到从服务器获取的状态时,我想隐藏警报。

【问题讨论】:

    标签: javascript angularjs frontend


    【解决方案1】:
    $scope.watch('[formname]', checkChanged, true)
    function checkChanged(newVal) {
        if (!angular.equals(newVal,$scope.data)) warnUser()
    }
    

    ^这将观察表单中的每个表达式并提醒用户

    【讨论】:

    • 您好,这种方法看起来不错,但不起作用。每次我在输入中输入内容时,oldValue 都会发生变化。
    • 尝试 $scope.formData = angular.copy($scope.data) 获取实际表单数据,并使用 $scope.data 进行比较。只是为了确保您没有在表单中插入对 $scope.data 的引用。
    • 您的带有复制功能的解决方案正在运行。谢谢你。这是我的全部代码:$scope.data = data.editedPage.jkOutputContainer.editedPage.pagesObject; $scope.formData = angular.copy($scope.data); $scope.$watch('data',function(newValue, oldValue) { if(!angular.equals(newValue, $scope.formData)) { $scope.dataHasChanged = true; } else { $scope.dataHasChanged = false; } }, true);
    【解决方案2】:

    要解决您的问题,请不要将服务器的响应绑定到 $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);
    });
    

    希望对您有所帮助!

    【讨论】:

    • 感谢您的快速回答。但是,它似乎不起作用。当我将 fromServer 作为 $scope.$watch 的参数传递时,它可以工作,但该函数仍会比较实际数据。当我在输入中输入内容时,开始成为 oldValue。另一方面,当我离开 $scope.$watch 参数并在条件下引用“fromServer”时,函数不起作用。
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 2017-08-20
    • 1970-01-01
    • 2015-05-28
    相关资源
    最近更新 更多