0

我有一个用于编辑附加在我的 DOM 根附近的项目的表单。我的页面包含这些项目的列表,以及编辑它们的链接。

最干净的方法是什么

  1. 单击编辑链接时在表单中显示所选项目
  2. 让表单在项目的副本上工作,以便在用户编辑时不会修改原件(并且可以取消更改)
  3. 保存表单会更新原始项目

我一直在玩 $rootScope、指令和服务的各种组合,但还没有一个可行的解决方案,更不用说一个干净的解决方案了。

4

2 回答 2

1

您可以首先使用指向与您正在编辑的对象具有相同属性的对象的 ngModel 绑定来设置表单。所以使用下面的对象,有一个带有ng-model='editObj.name'.

如果您关于项目的所有信息都存储在 JSON 对象中,则您只需选择该项目的一部分:

[
    {
        "name":"Tim",
        "country":"USA"
    },
    {
        "name":"second",
        "country":"CA"
    }
]

然后将第二个项目转移到一个新的作用域 obj 中:

$scope.editObjItem=angular.copy($scope.obj[1]);

然后您可以编辑它,然后在单击提交按钮时将其弹回原位,然后您可以根据需要将数据上传回服务器:

$scope.obj[1]=$scope.editObjItem;

如果用户在进行更改后取消编辑,则不会对原始对象造成损害。这就是我无论如何都会处理它的方式。

于 2013-03-31T14:44:19.413 回答
1

这是一个由控制器处理的非常简单的编辑表单。通过使用angular.copy( object/array)可以处理项目的副本。ng-submit=updateItem()然后在表单中使用已编辑副本中的值更新原始项目属性

<ul>
  <li ng-repeat="item in items"><button ng-click="editItem(item)">Edit</button>{{item.first}} {{item.last}} </li>
</ul>

 <form ng-submit="updateItem()" ng-show="activeItem">
 <h3>Edit Item</h3>
    <div><input ng-model="editCopy.first" type="text"/></div>
    <div><input ng-model="editCopy.last" type="text"/></div>
    <div><input type="submit" value="Update"/></div>
</form>  
app.controller('MainCtrl', function($scope) {
  /* utility function*/
  var swapItemValues=function(from,to){
      for(key in from){
        to[key]=from[key];
      }      
    }

  $scope.items=[{first:'SpongeBob', last:'SquarePants'} ];


    $scope.editItem=function(item){
      $scope.editCopy=angular.copy(item);      
      $scope.activeItem=item;/* reference to original item, used for form ng-show as well as to do update*/

    }

    $scope.updateItem=function(){
       swapItemValues( $scope.editCopy,$scope.activeItem );
       $scope.activeItem=null;/* form `ng-show` only displays when there is an activeItem*/
    }

});

演示:http ://plnkr.co/edit/O52EIk9ops8UqIFmbqXw?p=preview

Undo根据有问题的取消评论,稍微升级了 DEMO 并进行了编辑

http://plnkr.co/edit/c7H7lYBTnd2P6ShK7Ela?p=preview

于 2013-03-31T14:56:40.570 回答