我有一个显示项目的表格,允许内联编辑,可以保存或放弃更改。
每个表行包含显示未编辑行时项目内容的列,以及当行处于编辑模式时用于编辑的输入。
这是HTML:
<table class="table table-bordered">
<thead>
<tr>
<th>Field A</th>
<th>Field B</th>
<th>Field C</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>
<span ng-show="editingItem !== item">
{{item.fieldA}}
</span>
<input type="text" ng-model="item.fieldA" class="form-control" ng-show="editingItem === item" />
</td>
<td>
<span ng-show="editingItem !== item">
{{item.fieldB}}
</span>
<input type="text" ng-model="item.fieldB" class="form-control" ng-show="editingItem === item" />
</td>
<td>
<span ng-show="editingItem !== item">
{{item.fieldC}}
</span>
<input type="text" ng-model="item.fieldC" class="form-control" ng-show="editingItem === item" />
</td>
<td>
<i ng-click="startEditItem(item)" ng-show="editingItem !== item" class="fa fa-pencil link text-primary"></i>
<i ng-click="confirmEditItem(item)" ng-show="editingItem === item" class="fa fa-check link text-success "></i>
<i ng-click="cancelEditItem(item)" ng-show="editingItem === item" class="fa fa-times link text-danger"></i>
</td>
</tr>
</tbody>
</table>
控制器代码:
angular.module('myApp', [])
.controller('myController', function($scope) {
$scope.items = [{
id: '1',
fieldA: 'foo1',
fieldB: 'bar1',
fieldC: 'baz1'
}, {
id: '2',
fieldA: 'foo2',
fieldB: 'bar2',
fieldC: 'baz2'
}, {
id: '3',
fieldA: 'foo3',
fieldB: 'bar3',
fieldC: 'baz3'
}, ];
$scope.startEditItem = function(item) {
//clone, won't point to same reference
$scope.editingItemCopy = JSON.parse(JSON.stringify(item));
$scope.editingItem = item;
}
$scope.confirmEditItem = function() {
$scope.editingItem = null;
// no need to do anything, the model is changed already.
}
$scope.cancelEditItem = function(item) {
$scope.editingItem = null;
//below line doesn't work
//item = JSON.parse(JSON.stringify($scope.editingItemCopy));
for(var i = 0; i < $scope.items.length; i++) {
if($scope.items[i].id === item.id) {
$scope.items[i] = JSON.parse(JSON.stringify($scope.editingItemCopy));
}
}
}
});
我想知道为什么$ scope.cancelEditItem中的注释行无效,如果函数的传递参数应该指向数组中的同一元素,我必须修改$ scope.items数组。
这里是plunkr http://plnkr.co/edit/XF1ytvJ6HYfceaivZhfr?p=preview,请随意取消注释该行并对数组迭代进行注释以查看我正在谈论的内容。
答案 0 :(得分:1)
当您将对象分配给项目时,它与$scope.items[0] =
不同,并且您丢失了对$ scope.items的项目引用,您可以做的是操纵{{1}的对象即下面的代码将起作用,因为对象不会被其他对象破坏或覆盖,但它的属性值被修改
item
注意:您可以$scope.cancelEditItem = function (item) {
$scope.editingItem = null;
item = angular.extend(item, $scope.editingItemCopy);
}
JSON.parse(JSON.stringify(xxx))