How to save rows in a grid that I made a change to

user1943020 picture user1943020 · Jul 15, 2013 · Viewed 12.1k times · Source

I used ng-resource to get data from my server and then place the data into a table grid like this:

<div ng-form name="grid">
      <button type="submit" data-ng-disabled="grid.$pristine">Save</button>
        <div class="no-margin">
            <table width="100%" cellspacing="0" class="form table">
                <thead class="table-header">
                    <tr>
                        <th>ID</th>
                        <th>Title</th>
                    </tr>
                </thead>
                <tbody class="grid">
                    <tr data-ng-repeat="row in grid.data">
                        <td>{{ row.contentId }}</td>
                        <td><input type="text" ng-model="row.title" /></td>
                    </tr>
                </tbody>
            </table>
        </div>
</div>

Is there a way that I can make it so that clicking on the Submit button checks through the grid for the rows that changed and then calls a putEntity(row) function with the row as an argument?

Answer

refactorthis picture refactorthis · Jul 18, 2013

You could do it a few ways, and remember every NgModelController has a $dirty flag which can use to check if the input has changed. But I would say the easiest way is just to do this:

Edit to HTML:

<input type="text" ng-model="row.title" ng-change="row.changed=true" />
<button ng-click="save()">Save</button>

In JS:

$scope.save = function () {
    // iterate through the collection and call putEntity for changed rows
    var data = $scope.grid.data;
    for (var i = 0, len = data.length; i < len; i++) {
        if (data[i].changed) {
            putEntity(data[i]);
        }
    }
}