javascript - 在 AngularJS 中通过模态编辑对象 - 使用临时对象?

标签 javascript angularjs

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

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

模态中的 HTML:

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

这工作正常,模式显示(使用 ng-show)并且文本框填充了项目的名称。

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

然后是这个 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;
};

关于javascript - 在 AngularJS 中通过模态编辑对象 - 使用临时对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818235/

相关文章:

javascript - 执行ajax时如何将javascript变量值传递给jQuery validate() SubmitHandler

javascript - 将 $.get 包装在另一个延迟中

angularjs - 日历图标未在 angularjs 中打开日历

javascript - sails.js/angular 的复杂权限系统

javascript - 如何在 Angular Directive(指令)规范中使用 jasmine stub jquery 函数

javascript - 如何通过特定的Id删除内部子对象?

javascript - 最新版本中的 Ember.CollectionView API 是否有重大变化?

javascript - 在 jquery 中添加和删除类

javascript - JavaScript 中的 this() 是什么?

angularjs - ui-router 中嵌套状态的 URL 路由