简体   繁体   English

重置Angular 1.5视图模型

[英]Reset Angular 1.5 view model

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. 在这里,我在ng-model中使用vm.data来编辑每个字段。 But when ng-model edit vm.data, temp is also getting updated itself. 但是当ng-model编辑vm.data时,temp本身也会更新。 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. 因此,在调用vm.reset时,vm.data和temp相同,因此不会发生复位。

Please suggest a way to remove this varible scope refernce. 请提出一种删除此可变范围引用的方法。

Use angular.copy instead of assigning, = represents a reference whereas angular.copy() creates a new object as a deep copy. 使用angular.copy代替赋值, =表示引用,而angular.copy()创建一个新对象作为深层副本。

angular.copy(res, temp );

Your code will be, 您的代码将是

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

In javascript, objects are passed by reference. 在javascript中,对象是通过引用传递的。 So inside your service callback, you assign the same response object to both vm.data and temp. 因此,在服务回调中,您将相同的响应对象分配给vm.data和temp。 This way, while changing vm.data you are also changing temp, because both are pointing to the same memory location. 这样,在更改vm.data时,您同时也在更改温度,因为两者都指向相同的内存位置。

To make it work, assign separate instances (deep clone res object) to vm.data and temp. 要使其正常工作,请将单独的实例(深度克隆res对象)分配给vm.data和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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM