我使用ng-repeat指令顯示元素列表。每個元素都顯示在專用的div區塊中。我想允許塊編輯的意思是,當點擊編輯按鈕時,元素div的內容變成可以提交的表單...動態版列表項
我想遵循Angularjs哲學,意思是在控制器中沒有dom操作而是使用指令... ;-)
我使用ng-repeat指令顯示元素列表。每個元素都顯示在專用的div區塊中。我想允許塊編輯的意思是,當點擊編輯按鈕時,元素div的內容變成可以提交的表單...動態版列表項
我想遵循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>
在你的控制器,你可以有下面的代碼:
//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.
};
這種方式,可以實現在列表中的元素的顯示和編輯。請注意,將模型分配給輸入標籤已經改變了項目內容(我剛剛喜歡的AngularJS的一個特性 - 模型會自動更新,不需要進行明確的更新或保存) - 我僅提供它用於說明目的。
感謝您的回答!所以你需要隱藏/顯示div塊......在DOM中添加和刪除塊不是一個需要考慮的解決方案嗎? –
你也可以添加和刪除。查看可以在[這裏]找到的'ng-switch'指令(http://docs.angularjs.org/api/ng.directive:ngSwitch) – callmekatootie
寫完整的代碼是不可能的請讓我們知道你到目前爲止嘗試 –