如何检测Angular中复制对象的更改?

时间:2015-12-01 16:28:49

标签: javascript angularjs

我使用angular.copy克隆一个对象,以便我可以检测对象的更改,如下所示:



var app = angular.module('MyApp', []);
app.controller('MyCtrl', function ($scope) {
  $scope.obj = {
    id: 1,
    str: "Hello World"
  };
  $scope.init = function() {
    $scope.objCopy = angular.copy($scope.obj);
  }
  $scope.hasChanges = false;
  $scope.change = function () {
    $scope.hasChanges = !($scope.obj == $scope.objCopy);
  };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyCtrl" ng-init="init()">
      <input type="text" ng-model="objCopy.str" ng-change="change()" />
      <pre>obj = {{ obj }}</pre>
      <pre>objCopy = {{ objCopy }}</pre>
      <pre>hasChanges? {{ hasChanges }}</pre>
  </div>
</div>
&#13;
&#13;
&#13;

问题在于,虽然当我向文本字符串添加字符时,会检测到更改,但如果我将字符串编辑回其原始文本,则hasChanges变量仍会显示为true。我希望它成为false,因为字符串相等。他们不是吗?

2 个答案:

答案 0 :(得分:2)

使用角度等于

var app = angular.module('MyApp', []);
app.controller('MyCtrl', function ($scope) {
  $scope.obj = {
    id: 1,
    str: "Hello World"
  };
  $scope.init = function() {
    $scope.objCopy = angular.copy($scope.obj);
  }
  $scope.hasChanges = false;
  $scope.change = function () {
    $scope.hasChanges = !angular.equals($scope.obj, $scope.objCopy);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyCtrl" ng-init="init()">
      <input type="text" ng-model="objCopy.str" ng-change="change()" />
      <pre>obj = {{ obj }}</pre>
      <pre>objCopy = {{ objCopy }}</pre>
      <pre>hasChanges? {{ hasChanges }}</pre>
  </div>
</div>

答案 1 :(得分:1)

我认为你应该使用angular.equals而不是使用引用相等:

https://docs.angularjs.org/api/ng/function/angular.equals

而不是:

$scope.hasChanges = !($scope.obj == $scope.objCopy);

将其替换为:

$scope.hasChanges = !angular.equals($scope.obj, $scope.objCopy);

请尝试以下代码:

&#13;
&#13;
var app = angular.module('MyApp', []);
app.controller('MyCtrl', function ($scope) {
  $scope.obj = {
    id: 1,
    str: "Hello World"
  };
  $scope.init = function() {
    $scope.objCopy = angular.copy($scope.obj);
  }
  $scope.hasChanges = false;
  $scope.change = function () {
    $scope.hasChanges = !angular.equals($scope.obj, $scope.objCopy);
  };
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
  <div ng-controller="MyCtrl" ng-init="init()">
      <input type="text" ng-model="objCopy.str" ng-change="change()" />
      <pre>obj = {{ obj }}</pre>
      <pre>objCopy = {{ objCopy }}</pre>
      <pre>hasChanges? {{ hasChanges }}</pre>
  </div>
</div>
&#13;
&#13;
&#13;