通过AngularJS中的模态编辑对象-使用临时对象

Edit object via modal in AngularJS - use a temporary object?

本文关键字:临时对象 对象 编辑 AngularJS 模态 通过      更新时间:2023-09-26

场景:用户点击项目。以下代码运行并打开一个模态,其中包含一个填充了项目名称的文本框。

$scope.edit = function (item) {
    $scope.editingItem = { Name: item.Name };
};

模式中的我的HTML:

<input type="text" ng-model="editingItem.Name"/>

这很好,模态显示(使用ng-show),文本框填充项目名称。

我使用一个新对象来填充文本框,因为在按下保存按钮之前,我不希望原始对象发生更改(通过AngularJS自动数据绑定)

然后这个HTML:

<a href="" ng-click="update(editingItem)">Save</a>

导致:

$scope.update = function (item) {
    // What do I put in here to update the original item object that was passed
    // into the edit function at the top of this question?!
};

不过,我的问题是update方法中要放入什么?我想更新原始的item(保存在项目数组中)。

我会这样做:

$scope.edit = function (item) {
    $scope.editingItem = { Name: item.Name };
    $scope.originalItem = item;//store the instance of the item to edit
};
$scope.update = function (item) {
    $scope.originalItem.Name = item.Name;//copy the attributes you need to update
    //clear temp items to remove any bindings from the input
    $scope.originalItem = undefined;
    $scope.editingItem = undefined;
};