Reset Angular 1.5 view model

312 views Asked by At

I have a quite large from, I trying to reset it in button, but it did'nt work as expected.

See my code below

function someCtrl() {
    var temp;
    var vm = this;
    someService.then(function (res) {
        vm.data = res;
        temp = res;
    });

    vm.reset = function () {
        vm.data = temp; //so that vm will reset to res;
    }
}

Here I'm using vm.data in ng-model to edit each feild. But when ng-model edit vm.data, temp is also getting updated itself. Some varible scope reference is happening I guess. So when vm.reset is called vm.data and temp are same, so reset is not happening.

Please suggest a way to remove this varible scope refernce.

2

There are 2 answers

2
AudioBubble On BEST ANSWER

In javascript, objects are passed by reference. So inside your service callback, you assign the same response object to both vm.data and temp. This way, while changing vm.data you are also changing temp, because both are pointing to the same memory location.

To make it work, assign separate instances (deep clone res object) to vm.data and temp. Like this:

someService.then(function (res) {
    vm.data = angular.copy(res);
    temp = res; // no need to deep clone this one. temp can point to the res obj
});

And change the reset function to this

vm.reset = function () {
    vm.data = angular.copy(temp); // assign "backup" value to vm.data
}
3
Sajeetharan On

Use angular.copy instead of assigning, = represents a reference whereas angular.copy() creates a new object as a deep copy.

angular.copy(res, temp );

Your code will be,

 someService.then(function (res) {
        vm.data = res;
        angular.copy(res, temp );
 });