单击checkAll复选框,将其对象推入另一个数组对象并从现有数组中删除

时间:2016-07-05 17:50:44

标签: javascript arrays angularjs

我想实现的功能是当我点击“全选”复选框时,我想在新数组中推送所选项目并从当前项目中删除。

尝试使用拼接功能,但无法删除第一个表中的所有项目。

enter code here这是我创建的sample plnkr,所以当我点击第一张表中的“全选”时,其所有项目都应该在“新表格”中推送并同时删除来自“第一张桌子(名为旧桌子)

2 个答案:

答案 0 :(得分:1)

这将清除您的数组并推送$ scope.merged中的所有条目

$scope.pushlist = function(data){
    for(var item of data){
        $scope.merged.push({"name":item.name});
    }
    data.length=0
};

答案 1 :(得分:0)

  

使用angular.copy制作对象的副本

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