gpt4 book ai didi

angularjs - 数组中的 Angular 更新对象

转载 作者:行者123 更新时间:2023-12-03 23:26:15 24 4
gpt4 key购买 nike

我想更新对象数组中的对象。除了迭代所有项目并更新匹配的项目之外,还有另一种可能性吗?当前代码如下所示:

angular.module('app').controller('MyController', function($scope) {
$scope.object = {
name: 'test',
objects: [
{id: 1, name: 'test1'},
{id: 2, name: 'test2'}
]
};

$scope.update = function(id, data) {
var objects = $scope.object.objects;

for (var i = 0; i < objects.length; i++) {
if (objects[i].id === id) {
objects[i] = data;
break;
}
}
}
});

最佳答案

将项目传递给您的更新方法。看看下面的示例。

function MyCtrl($scope) {
$scope.items =
[
{name: 'obj1', info: {text: 'some extra info for obj1', show: true}},
{name: 'obj2', info: {text: 'some extra info for obj2', show: false}},
];
$scope.updateName = function(item, newName){
item.name = newName;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app>
<table ng-controller="MyCtrl" class="table table-hover table-striped">
<tr ng-repeat="x in items">
<td> {{ x.name }}</td>
<td>
<a href="#" ng-show="!showUpdate" ng-click="someNewName = x.name; showUpdate = true">Update</a>
<div ng-show="showUpdate" ><input type="text" ng-model="someNewName"> <input type="button" value="update" ng-click="updateName(x, someNewName); showUpdate = false;"></div>
</td>
</tr>

</table>
</body>

关于angularjs - 数组中的 Angular 更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com