Javascript 列表项的动态编辑
我使用ng repeat指令显示元素列表。每个元素都显示在专用的div块中。我想允许块编辑,这意味着当点击编辑按钮时,元素div的内容变成了一个可以提交的表单Javascript 列表项的动态编辑,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我使用ng repeat指令显示元素列表。每个元素都显示在专用的div块中。我想允许块编辑,这意味着当点击编辑按钮时,元素div的内容变成了一个可以提交的表单 我希望遵循Angularjs哲学,即在控制器中不进行dom操作,而是使用指令…;-) 一种方法是有条件地将元素显示为只读或表单。它看起来像这样: <div ng-repeat="item in list"> <div ng-hide="editMode(item.id)"> <!--
我希望遵循Angularjs哲学,即在控制器中不进行dom操作,而是使用指令…;-) 一种方法是有条件地将元素显示为只读或表单。它看起来像这样:
<div ng-repeat="item in list">
<div ng-hide="editMode(item.id)">
<!-- This will contain the DOM elements that
will only display the item -->
<span>item.text</span>
<button type="button" ng-click="changeToEditMode(item.id)">
Edit
</button>
</div>
<div ng-show="editMode(item.id)">
<!-- This will contain DOM elements that will
allow editing the item -->
<input type="text" ng-model="item.text">
<button type="button" ng-click="editItem(item)">
Save
</button>
</div>
</div>
通过这种方式,您可以实现列表中元素的显示和编辑。注意,将模型分配给输入标记已经改变了项目内容(AngularJS的一个特性,我非常喜欢——模型是自动更新的,不需要显式更新或保存)-我提供它只是为了说明目的。编写完整的代码是不可能的,请让我们知道您尝试了什么,谢谢您的回答!所以您需要隐藏/显示div块。。。在DOM中添加和移除块不是一个需要考虑的解决方案,也可以添加和移除。查看可找到的ng开关指令
//The list of elements
//Id is needed to uniquely identify an item in the list
$scope.list = [
{
id: 1,
text: "item_1"
},
{
id: 2,
text: "item_2"
}
];
//Contains the ID of the item currently being edited
//You can have single item that can be in edit mode at one time or
//you can have multiple items open in edit mode. Go with an array for the latter
//By default, no item is in edit mode
$scope.itemIdForEdit = 0;
//Checks if the item is in edit mode
$scope.editMode = function (itemId) {
return $scope.itemForEdit === itemId;
};
//Changes the item being edited
$scope.changeToEditMode = function (itemId) {
$scope.itemForEdit = itemId;
};
//Edits the item
$scope.editItem = function (item) {
//Logic to update the item in the $scope.list or backend.
};