如何在ng-repeat中创建所选行的数组?

时间:2016-12-20 12:55:05

标签: javascript angularjs arrays angularjs-ng-repeat

我的Angular应用程序中有一张表。表的每一行都有一个复选框,我想在数组中推送所有选定的行。 这是我的HTML代码:

<table class="group-tbl">
  <thead>
    <td>
      <label for="select_all"><span id="select-all-btn">&#xf35f;</span></label>
      <input type="checkbox" ng-model="all" id="select_all">
    </td>
    <td>Name</td>
    <td>company</td>
    <td>Email</td>
    <td>Mobile</td>
    <td></td>
  </thead>
  <tr ng-repeat="y in subscriberDetail|filter:search | limitTo:settings.pageLimit:settings.offset">
    <td>
      <input id="{{cb+$index}}" type="checkbox" ng-checked="all" ng-model="y.check" name="group_item-select">
      <label for="{{cb+$index}}"><span></span> </label>
    </td>
    <td ng-class="{'greent': y.check}">{{y.nameFamily }}</td>
    <td ng-class="{'greent': y.check}">{{y.company }}</td>
    <td ng-class="{'greent': y.check}">{{y.email}}</td>
    <td ng-class="{'greent': y.check}">{{y.mobile}}</td>
    <td class="group-tbl__btn" ng-controller="subscriberDeleteController as subdel"><a href="#/group/detail/{{data.categoryId}}/detailView/{{y.id}}" class="btn">&#xf133;</a><a ng-show="y.usersId==usersId" href="#/group/detail/{{data.categoryId}}/editSub/{{y.id}}" class="btn" style="font-size: .8em">Edit</a>
      <button ng-show="y.usersId==usersId || y.status==1"
      class="btn" ng-value="{{y.id}}" ng-click="confirm(subscriberDetail,settings.offset+$index);getValue()" button-value="deleteId">&#xf4c4;</button>
    </td>
  </tr>
</table>

2 个答案:

答案 0 :(得分:3)

点击

进行更新

ng-click添加到您的输入中:

<input type="checkbox" ng-model="y.check" ng-click="click(y)">

以下是控制器中click()的代码:

$scope.click = function(item) {
    if(item.check) { // Add it
        $scope.selected.push(item);
    } else { // Remove it
        var index = $scope.selected.indexOf(item);
        $scope.selected.splice(index, 1);
    }
}

=> Demo on JsFiddle <=

替代for循环

循环使用几种方法。这是一个带有简单for(;;)循环的代码。

// Array for selected rows
$scope.selected = [];

// For each item in subscriberDetail
for(var i = 0; i < $scope.subscriberDetail.length; i+) {
    // Item is checked
    if($scope.subscriberDetail[i].check == true) {
        // Add it to the selected array
        $scope.selected.push($scope.subscriberDetail[i]);
    }
}

此代码应在选择的结尾处调用。另外,请看第二个解决方案。

=> Demo on JsFiddle <=

答案 1 :(得分:1)

虽然@Mistalis的答案已经足够,但是当您确实需要选中的项目时,也可以使用过滤器执行此操作。这样您就不必跟踪数组或切换复选框时:

$scope.onSomeActionWhenYouNeedTheCheckedItems = function(){
    var checkedItems = $filter("filter")($scope.subscriberDetail, { check: true });
    // do something with the checked items
}

或者在您看来:

<div ng-repeat="checkedItem in checkedItems = (subscriberDetail | filter:{check:true})">
    <!-- ... -->
</div>

最后一种语法还会在您的范围内创建变量checkedItems,因此您无需手动执行任何操作。