user2217057
user2217057

Reputation: 237

AngularJS - update value of input box in a dynamic table on button click

After having checked various Stackoverflow resources, it looks like I am still unable to figure out the Angular way of doing this. The HTML table, which has just an Id column and another text column (input box), is dynamically populated via ng-repeat. Then I provide "update" and "delete" functions/buttons for each individual record showing inside input box. 'Delete' function seems OK, on 'delete' button click I just pass the ID to the function as argument. With 'update' click event, I am not sure how to pass the value of the input box to the function as a second argument. Please see the simplified markup and code below.

<tr ng-repeat="rec in allRecords">
    <td>{{rec.Id}}</td>
    <td>
        <button ng-click="update(rec.Id, HERE_TEXT_FROM_SIBLING_INPUT')">Update</button>
        <input type="text" value="{{rec.Name}}">
        <button ng-click="deleteMonitorGroup(rec.Id)">Delete</button>
    </td>

And the controller

app.controller('MyCtrl', function (MyService, $scope) {

MyService.listAllRecords(function (allRecs) {
    $scope.allRecords= allRecs;
});

$scope.update = function (Id, text) {

        MyService.update(Id, text, function () {
           // update record
        });
}

});

Any help is appreciated.

Upvotes: 3

Views: 2505

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Use ng-model there on input fields like ng-model="rec.Name" which keep rec.Name updated by angular two way binding feature.Then do pass ng-model's rec.Name to the updated function OR rather just pass rec object on function call to make it more simpler.

Markup

<tr ng-repeat="rec in allRecords">
    <td>{{rec.Id}}</td>
    <td>
        <button ng-click="update(rec)">Update</button>
        <input type="text" ng-model="rec.Name">
        <button ng-click="deleteMonitorGroup(rec.Id)">Delete</button>
    </td>
</tr>

Upvotes: 3

Related Questions