我想在ng-repeat指令中更新用户名。如果我采用变量但无法在数组中执行此操作,则可以进行编辑。这里title
是一个变量,users
是一个数组。我想更新用户名
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app>
<div ng-controller="ClickToEditCtrl">
<div ng-hide="editorEnabled">
{{title}} {{name}}
<br>users
<ul> <li ng-repeat="(key,u) in users">
{{key+1}} name: {{u.name}} <a href="#" ng-click="enableEditor(u.name)">Edit title</a>
</li></ul>
</div>
<div ng-show="editorEnabled">
<input ng-model="editableTitle" ng-show="editorEnabled"><br><br>
<input ng-model="editableUserName" ng-show="editorEnabled">
<a href="#" ng-click="save()">Save</a>
or
<a href="#" ng-click="disableEditor()">cancel</a>.
</div>
</div>
</div>
<script>
function ClickToEditCtrl($scope) {
$scope.title = "Welcome to this demo!";
$scope.users = [{'name':'A'},{'name':'B'}];
$scope.editorEnabled = false;
$scope.enableEditor = function(name) {
$scope.editorEnabled = true;
alert(name);
$scope.editableTitle = $scope.title;
$scope.editableUserName = name
};
$scope.disableEditor = function() {
$scope.editorEnabled = false;
};
$scope.save = function() {
$scope.title = $scope.editableTitle;
$scope.users.name = $scope.editableUserName;
$scope.disableEditor();
};
}
</script>`
`
答案 0 :(得分:1)
对于您正在编辑的用户的编辑传递:
<a href="#" ng-click="enableEditor(u)">Edit title</a>
然后存储对该用户的引用。
var editableUser;
$scope.enableEditor = function(user) {
$scope.editorEnabled = true;
$scope.editableTitle = $scope.title;
$scope.editableUserName = user.name;
editableUser = user;
};
然后在保存中,将更改保存到用户:
$scope.save = function() {
$scope.title = $scope.editableTitle;
editableUser.name = $scope.editableUserName;
$scope.disableEditor();
};
答案 1 :(得分:1)
理想情况下,您希望拥有一个不会更改与每个用户相关联的ID。
这个plunker是你的回答plunker
我已经离开并使用数组的$ index作为id,但理想情况下你应该给每个用户一个id
ng-click="enableEditor($index)"
我还修改了一些函数来记录索引