Aparna Aparna - 5 months ago 40
AngularJS Question

On click of checkAll checkbox, push its objects in another array object and remove from existing array

Functionality I want to implement is that when I click on "select All" checkbox, I want to push the selected item in new array and delete from current one.

Tried with splice function, but not able to delete all items from the first table.

enter code here
Here is the sample plnkr I have created, So when I click on "select All" from first table, all its items should get pushed in "New Table" and at the same time removed from "First table(named Old table)

Answer

Use angular.copy to make an copy of the object

var app = angular.module("myApp", []);

app.controller("SecondCtrl", function($scope) {
  $scope.merged = [];
  $scope.data = [{
    "name": "ABC",
    "selected": false
  }, {
    "name": "HJK",
    "selected": false
  }, {
    "name": "PQR",
    "selected": false
  }, {
    "name": "LMN",
    "selected": false
  }];

  $scope.selectall = function(checkAll) {
    if (checkAll) {
      $scope.merged = angular.copy($scope.data);
      $scope.data.length = 0;
    } else {
      $scope.data = angular.copy($scope.merged);
      $scope.merged.length = 0;
    }
  };
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script>
<div ng-app="myApp" ng-controller="SecondCtrl">
  <div>
    <h1>Old Table</h1>
    <table>
      <thead>
        <th>
          <input type="checkbox" ng-click="selectall(checkAll)" ng-model="checkAll">Select All</th>
        <th>Name</th>
      </thead>
      <tbody>
        <tr ng-repeat="item in data">
          <td>
            <input type="checkbox" ng-model="item.selected">
          </td>

          <td>{{item.name}}</td>
        </tr>
      </tbody>
    </table>
  </div>
  <hr>
  <div>
    <h2>New Table</h2>
    <table ng-show="merged">
      <thead>
        <th>Name</th>
      </thead>
      <tbody>
        <tr ng-repeat="item in merged">
          <td>{{item.name}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Fiddle Demo