vendredi 3 juin 2016

Angular editable table update model on button click

I want to have a table that will switch to edit mode when row is clicked. So I did a template with rows with both versions of cell content for view and edit mode.

<div class="container" ng-controller="locationPropertiesController">
    <div class="row">

        <input type="text" ng-model="filter" />

        <button class="btn btn-default" ng-click="events.getLocations()">Filter</button>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>
                        Site name
                    </th>
                    <th>
                        Time zone
                    </th>
                    <th>
                    </th>
                </tr>
            </thead>
            <tr ng-repeat="r in locations">
                <td ng-click="events.startEdit($index)">
                    <span ng-hide="r.editMode"></span>
                    <input ng-show="r.editMode" type="text" value="" />
                </td>
                <td ng-click="events.startEdit($index)">
                    <span ng-hide="r.editMode"></span>
                    <input ng-show="r.editMode" type="text" value="" />
                </td>
                <td>
                    <button ng-show="r.editMode" class="btn btn-default" ng-click="events.updateLocation($index)">Update</button>
                    <button ng-show="r.editMode" class="btn btn-default" ng-click="events.cancelEdit($index)">Cancel</button>
                </td>
            </tr>
        </table>

    </div>
</div>

I used ng-bind ( ) syntax because I don't know any better way to prevent an update of the source model till someone clicks "Update" button. This way if you click "Cancel" the textboxes for edit will just disappear, and the model will stay unchanged.

I don't know, maybe there are better options for this, I'm open for suggestions, but now there is a better problem. Now, as I don't do two-way binding I will have to find the specific row and take the values from dom elements manual, and assign them back to the model.

This is another possible point of failure when, in future, the table will have to be extended by a developer, and also, I wouldn't like to reinvent the wheel.

Are there good patterns and practices for that? How could I redesign this?

Thanks.

Aucun commentaire:

Enregistrer un commentaire