Reset a model with angular.js

Mosh FeuAwea提出了一个问题:Reset a model with angular.js,或许与您遇到的问题类似。

回答者Mosh FeuMark Rajcok给出了该问题的处理方式:

This is really a question about JavaScript (so I added the "javascript" tag). When a JavaScript object (such as array $scope.initial) is assigned to a variable, it is assigned by reference, not by copy. So, this statement

$scope.datas= $scope.initial;

results in $scope.datas pointing to the $scope.initial object. Any changes that are made to $scope.datas or $scope.initial both affect the same (single) object. Since ng-model is used to data-bind object elements data1 and data2, any changes to the text inputs will change the data1 and data2 elements of the object that $scope.datas references -- i.e., $scope.initial. To see this in action, add the following to your fiddle's HTML:

<p>{{initial}}</p>

When you change the values in the text boxes, you'll see that $scope.initial is also changing.

@Max provided a partial answer: use angular.copy() in the reset function. However, you'll also have to use angular.copy() in the initial assignment too:

 $scope.datas = angular.copy($scope.initial);

Update:

As @EpokK shows in his answer, an alternate solution is

angular.copy($scope.initial, $scope.datas);

As @bekite mentions in his answer, @EpokK's solution does not create another object.

The full code

angular.module('app', []).controller('MyCtrl', function($scope) {
  $scope.initial = [{
    data1: 10,
    data2: 20
  }];
  $scope.datas = angular.copy($scope.initial);
  $scope.reset = function () {
    $scope.datas = angular.copy($scope.initial);
    // or
    // angular.copy($scope.initial, $scope.datas);
  }
});<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="MyCtrl">
  <div ng-repeat="data in datas">
    <input type="text" ng-model="data.data1" />
    <input type="text" ng-model="data.data2" />
  </div> 
  <a ng-click="reset()">Reset to initial value</a>
  or
  <hr />
  <p ng-repeat="data in datas">{{data.data1}}, {{data.data2}}</p>{{initial}}
</div>

fiddle

希望本文对你有帮助,欢迎支持JavaScript中文网