动态编辑列表项

时间:2013-06-27 09:28:05

标签: javascript angularjs angularjs-directive

我使用ng-repeat指令显示元素列表。每个元素都显示在专用div块中。我想允许块编辑,这意味着当点击编辑按钮时,元素div的内容将成为可以提交的表单...

我想遵循Angularjs哲学意味着在控制器中没有dom操作,而是使用指令......; - )

1 个答案:

答案 0 :(得分:1)

这样做的一种方法是有条件地显示元素 - 或者只读或作为表单。它看起来像这样:

<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的一个特性 - 模型自动更新,无需显式更新或保存) - 我提供它仅用于说明目的。