转载于:http://www.cnblogs.com/smilecoder/articles/6516787.html
angular1.x 简单的全选功能
1.样子
2.代码实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css"/>
<script type="text/javascript" src="jq/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="angular/angular-1.5.0.min.js"></script>
<script type="text/javascript" src="angular/angular-route.min.js"></script>
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div ng-app="testModule" >
<div ng-controller="testController">
<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.orgCompanyName}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
<script>
var m1 = angular.module('testModule', ['ngRoute']);
m1.controller("testController", ["$scope", "$location", function ($scope, $location) {
//设置基本信息
$scope.content = [
{
id: 10,
baseInfo: {
name: 'hanker'
},
orgCompanyName : 'ali'
},
{
id: 11,
baseInfo: {
name: 'hanker'
},
orgCompanyName : 'ali'
},
{
id: 12,
baseInfo: {
name: '222'
},
orgCompanyName : 'ali'
},
{
id: 13,
baseInfo: {
name: 'hanker111'
},
orgCompanyName : 'baidu'
},
{
id: 14,
baseInfo: {
name: 'eeee'
},
orgCompanyName : 'tenxun'
}
];
//创建变量用来保存选中结果
$scope.selected = [];
//动作 和 id号 如果是add则把id号放入 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) {
console.log( id );
var checkbox = $event.target;
console.log( checkbox );
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
//全选操作
$scope.selectAll = function ($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
// 遍历这个 content 把所有的元素从selected中添加或删除
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;
};
}]);
</script>