gpt4 book ai didi

javascript - 更换时 Angular 模型不更新

转载 作者:行者123 更新时间:2023-11-28 13:29:28 26 4
gpt4 key购买 nike

This Plunkr展示了我遇到的问题。

我有一个在对话框及其父页面中显示的数组。在对话框范围内修改该数组效果很好,但是当我完全替换该数组时,更改只能在对话框范围内看到。这是为什么?

我的代码,以防 Plunkr 吃掉它:

angular.module('app', ['ui.bootstrap'])
.controller('demoController', function($modal) {
var vm = this;

vm.message = 'Binding Problems';
vm.list = [1,2,3];

vm.modal = function() {
$modal.open({
controller: 'modalController as vm',
templateUrl: 'modal.html',
resolve: {
list: function() {
return vm.list;
}
}
});
};
})
.controller('modalController', ['$modalInstance', '$scope', 'list',
function($modalInstance, $scope, list) {
var vm = this;

vm.list = list;
vm.modalText = 'Modal Text';

vm.cancel = function() {
$modalInstance.dismiss();
};
vm.clear = function() {
vm.list = []; // This does not propagate to the parent controller...
};

vm.add = function() {
vm.list.push(4); // ...but this does.
};

}
]);

更新: Plunkr has been updated好的,所以我明白现在发生了什么,但不知道如何在我的代码中修复它。在我的实际代码中,我用 AJAX 调用的结果替换数据。我想在这种情况下我有几个选项,例如 vm.list.length = 0 然后 push() 从 AJAX 调用返回的每个项目,但是看起来效率极低。这通常是如何完成的?

最佳答案

不用在 clear() 方法中重新创建数组,只需清空它即可:

vm.clear = function() {
vm.list.length = 0;
};

here是工作中的笨蛋

关于javascript - 更换时 Angular 模型不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26281326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com