繁体   English   中英

重置Angular 1.5视图模型

[英]Reset Angular 1.5 view model

我有一个很大的尝试,我试图在按钮中重置它,但是它没有按预期工作。

请参阅下面的代码

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;
    }
}

在这里,我在ng-model中使用vm.data来编辑每个字段。 但是当ng-model编辑vm.data时,temp本身也会更新。 我猜正在发生一些可变范围参考。 因此,在调用vm.reset时,vm.data和temp相同,因此不会发生复位。

请提出一种删除此可变范围引用的方法。

使用angular.copy代替赋值, =表示引用,而angular.copy()创建一个新对象作为深层副本。

angular.copy(res, temp );

您的代码将是

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

在javascript中,对象是通过引用传递的。 因此,在服务回调中,您将相同的响应对象分配给vm.data和temp。 这样,在更改vm.data时,您同时也在更改温度,因为两者都指向相同的内存位置。

要使其正常工作,请将单独的实例(深度克隆res对象)分配给vm.data和temp。 像这样:

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
});

并将重置功能更改为此

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