Reset a model with angular.js

前端 未结 7 1000
一生所求
一生所求 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:45

    I love Yasser's comment: clear and concise.

    I definitely prefer copying the value when starting to edit, and then just replacing the reference on cancel/save.

    I prefer binding on a local copy, and not the original data, and then changing the final data only on save. This prevent all sorts of bugs later, and encapsulates the edit behavior.

    The final version would be:

    function initValue() {
        $scope.bound = angular.copy($scope.data);
    }
    
    function setValue() {
        $scope.data = $scope.bound;
    }
    
    $scope.edit = function () {
        $scope.editing = true;
        initValue();
    };
    
    $scope.cancel = function () {
        $scope.editing = false;
        initValue();
    };
    
    $scope.save= function () {
        $scope.editing = false;
        setValue();
    };
    

提交回复
热议问题