重置Angular 1.5视图模型

时间:2016-12-30 09:43:45

标签: javascript angularjs angular-components angularjs-1.5

我有一个非常大的,我试图在按钮中重置它,但它确实按预期工作。

请参阅下面的代码

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是相同的,所以不会发生重置。

请建议一种方法来删除此变量范围参考。

2 个答案:

答案 0 :(得分:1)

使用 angular.copy 代替分配, = 代表参考,而 angular.copy() 创建新对象作为深层复制。

angular.copy(res, temp );

您的代码将是,

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

答案 1 :(得分:1)

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

要使其工作,请将单独的实例(深度克隆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
}