首页 > 编程技术 > js

Angular多选、全选、批量选择操作实例代码

发布时间:2017-3-13 10:00

在前台开发过程中,列表批量选择是一个开发人员经常遇到的功能,列表批量选择的实现方式很多,但是原理基本相同,本文主要来讲AngularJs如何简单的实现列表批量选择功能。

首先来看html代码

<table cellpadding="0" cellspacing="0" border="0" class="datatable table table-hover dataTable">
      <thead>
      <tr>
        <th><input type="checkbox" ng-click="selectAll($event)" ng-checked="isSelectedAll()"/></th>
        <th>姓名</th>
        <th>单位</th>
        <th>电话</th>
      </tr>
      </thead>
      <tbody>
      <tr ng-repeat="item in content">
        <td><input type="checkbox" name="selected" ng-checked="isSelected(item.id)" ng-click="updateSelection($event,item.id)"/></td>
        <td>{{item.baseInfo.name}}</td>
        <td>{{item.orgCompanyName}}</td>
        <td>{{item.baseInfo.mobileNumberList[0].value}}</td>
      </tr>
      </tbody>
    </table>

html里面简单建立一个表格,与批量选择相关的只有两处。

一处是第3行 ng-click="selectAll($event)" ,用来做全选的操作; ng-checked="isSelectedAll() 用来判断当前列表内容是否被全选。

一处是第12行 ng-click="updateSelection($event,item.id) ,用来对某一列数据进行选择操作; ng-checked="isSelected(item.id) 用来判断当前列数据是否被选中。

然后需要在与该页面相对应的controller中实现与批量选择相关的方法

//创建变量用来保存选中结果
          $scope.selected = [];
          var updateSelected = function (action, id) {
            if (action == 'add' && $scope.selected.indexOf(id) == -1) $scope.selected.push(id);
            if (action == 'remove' && $scope.selected.indexOf(id) != -1) $scope.selected.splice($scope.selected.indexOf(id), 1);
          };
          //更新某一列数据的选择
          $scope.updateSelection = function ($event, id) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            updateSelected(action, id);
          };
          //全选操作
          $scope.selectAll = function ($event) {
            var checkbox = $event.target;
            var action = (checkbox.checked ? 'add' : 'remove');
            for (var i = 0; i < $scope.content.length; i++) {
              var contact = $scope.content[i];
              updateSelected(action, contact.id);
            }
          };
          $scope.isSelected = function (id) {
            return $scope.selected.indexOf(id) >= 0;
          };
          $scope.isSelectedAll = function () {
            return $scope.selected.length === $scope.content.length;
          };

controller中主要是对html中用到的几个方法的实现,相对来讲实现代码还是比较简洁易懂的。

多选效果展示如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

标签:[!--infotagslink--]

您可能感兴趣的文章: