Reset a model with angular.js

前端 未结 7 1001
一生所求
一生所求 2020-12-02 17:03

I\'m simply try to reset values like this :

$scope.initial = [
    {
        data1: 10,
        data2: 20
    }            
];


$scope.datas= $scope.initial         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-02 17:52

    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:

    {{initial}}

    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);
      }
    });
    
    
    
    Reset to initial value or

    {{data.data1}}, {{data.data2}}

    {{initial}}

    fiddle

提交回复
热议问题