编辑对传递参数的引用;t更新模型
Editing reference to passed argument doesn't update model
我有一个表,它显示项目并允许内联编辑,并能够保存或放弃更改。
每个表行都包含列,这些列在未编辑行时显示项目的内容,在行处于编辑模式时显示用于编辑的输入。
这是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数组。
这是plunkerhttp://plnkr.co/edit/XF1ytvJ6HYfceaivZhfr?p=preview,可以随意取消对该行的注释,并对数组迭代进行注释,看看我在说什么。
当您将对象分配给项目时,它与$scope.items[0] =
不同,并且您丢失了对$scope.items的项目引用,您可以做的是操作item
的对象,即以下代码将工作,因为对象不会被其他对象破坏或覆盖,但其属性值会被修改
$scope.cancelEditItem = function (item) {
$scope.editingItem = null;
item = angular.extend(item, $scope.editingItemCopy);
}
注意:您可以执行angular.copy(xxx)
而不是JSON.parse(JSON.stringify(xxx))
相关文章:
- 视图ngValue-Angular JS中未更新模型的更改
- 需要使用触摸屏从 AngularJS 指令中更新模型
- 角度指令没有更新模型视图
- 复选框仅在第二次单击后更新模型
- Angular.js-Socket.io事件更新模型,而不是视图
- UI Select在删除后不会更新模型
- 为什么ng提交没有提交和更新模型
- AngularJS-基于URL更新模型
- 视图更改时,Ember.js更新模型
- Knockoutjs函数更新模型时应出现异常
- 挖空绑定不会更新模型
- 范围不更新模型中的更改
- 导航时更新模型变量
- 角度.js更新模型
- Ember.js不更新模型
- 在使用挖空自定义绑定时更新模型时更新元素
- 在自我更新时以ng重复更新模型
- 如何在主干中对列表进行排序时更新模型的顺序属性
- AngularJS 复选框不更新模型
- 更新模型中的数据不会绑定到控制器