Codelife
Codelife

Reputation: 185

Delete a row from a table using AngularJS

I want to delete a row from a table in AngularJS. Data in the table coming from api.json file. If i click on checkbox and then Delete button, it should be deleted. Also, i want to restrict the selection. Suppose, if i click on checkbox in first row, then it will be unchecked if i click in any other row. So, one time, only one row should be selected. This is the plnkr link :-

http://plnkr.co/edit/UzvucP5T9ijpIP4iDLrt?p=preview

This is the html structure, I am not sure where to place the checkbox.

<div ng-app="MyApp" ng-controller="displayController">
      <table style="width:100%" >
        <tr ng-repeat="data in datas">
          <td>
            <input type="checkbox" ng-model="data.clicked">
          </td>
          <td>{{ data.venture }}</td>
          <td>{{ data.message }}</td>
        </tr>
      </table>
    </div>
    <button ng-click="delete()">DELETE</button>

Upvotes: 0

Views: 953

Answers (2)

Rohit Shedage
Rohit Shedage

Reputation: 25930

To have only one checkbox, you can follow following steps

change your html to

<tr ng-repeat="(key, data) in datas">

      <td>
        <input type="checkbox" ng-model="data.clicked" ng-change="changed(key)">
      </td>
      <td>{{ data.venture }}</td>
      <td>{{ data.message }}</td>
    </tr>

and add changed function as

$scope.changed = function (changedKey) {

    angular.forEach($scope.datas, function(val, key){
          if(changedKey !== key){
            $scope.datas[key].clicked =false;
          }
        })
  };

Upvotes: 0

Rohit Shedage
Rohit Shedage

Reputation: 25930

<button ng-click="delete()">DELETE</button> is out of scope of controller Consider moving button inside div as it will fall under controller

Your code should look something like this

<div ng-app="MyApp" ng-controller="displayController">

  <table style="width:100%" >
    <tr ng-repeat="data in datas">
      <td>
        <input type="checkbox" ng-model="data.clicked">
      </td>
      <td>{{ data.venture }}</td>
      <td>{{ data.message }}</td>
    </tr>
  </table>
  <button ng-click="delete()">DELETE</button>
</div>

Upvotes: 0

Related Questions