AngularJS实现全选反选功能

AngularJS是为了克服HTML在构建应用上的不足而设计的。HTML是一门很好的为静态文本展示设计的声明式语言,但要构建WEB应用的话它就显得乏力了。所以我做了一些工作(你也可以觉得是小花招)来让浏览器做我想要的事。

这里用到AngularJS四大特性之二----双向数据绑定

注意:没写一行DOM代码!这就是ng的优点,bootstrap.css为了布局,JS代码也只是简单创建ng模块和ng控制器

效果:

<!DOCTYPE html>

<html lang="en" ng-app="myModule5"><!--3、ng-app="myModule5"启动ng并调用模块-->

<head>

<meta charset="UTF-8">

<link rel="stylesheet" href="css/bootstrap.css">

<title>全选/取消全选</title>

</head>

<body>

<div class="container" ng-controller="myCtrl5"><!--4、ng-controller="myCtrl5"启用控制器-->

<h2>全选和取消全选</h2>

<table class="table table-bordered">

<thead>

<tr>

<th>选择</th>

<th>姓名</th>

<th>操作</th>

</tr>

</thead>

<tbody>

<tr>

<td>

<input ng-checked="selectAll" type="checkbox">

</td>

<td>Tom</td>

<td>

<button class="btn btn-danger btn-xs">删除</button>

</td>

</tr>

<tr>

<td>

<input ng-checked="selectAll" type="checkbox">

</td>

<td>Mary</td>

<td>

<button class="btn btn-danger btn-xs">删除</button>

</td>

</tr>

<tr>

<td>

<input ng-checked="selectAll" type="checkbox">

</td>

<td>King</td>

<td>

<button class="btn btn-danger btn-xs">删除</button>

</td>

</tr>

</tbody>

</table>

<input type="checkbox" ng-model="selectAll">

<span ng-hide="selectAll">全选</span>

<span ng-show="selectAll">取消全选</span>

</div>

<script src="js/angular.js"></script><!--1、引入angularJS-->

<script>

//2、创建自定义模块和控制器

angular.module('myModule5', ['ng']).

controller('myCtrl5', function($scope){

});

</script>

</body>

</html>

ps:AngularJs 简单实现全选,多选操作

很多时候我们在处理CURD(增删改查)的时候需要实现批量操作数据,这时候就必须使用多选操作。

Angular 中实现如下(当然还有很多种比笔者写的更好的方法,这里只是简单的实现。)

HTML:

<section>

<pre>{{choseArr}}</pre>

全选: <input type="checkbox" ng-model="master" ng-click="all(master,tesarry)">

<div ng-repeat="z in tesarry">

<input id={{z}} type="checkbox" ng-model="x" ng-checked="master" ng-click="chk(z,x)">{{z}}

</div>

<a href="#" class="btn btn-danger" ng-click="delete()" > 删除</a>

</section>

页面效果如下:(CSS采用bootstrap) 

JS代码:

$scope.tesarry=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘];//初始化数据

$scope.choseArr=[];//定义数组用于存放前端显示

var str="";//

var flag=‘‘;//是否点击了全选,是为a

$scope.x=false;//默认未选中

$scope.all= function (c,v) {//全选

if(c==true){

$scope.x=true;

$scope.choseArr=v;

}else{

$scope.x=false;

$scope.choseArr=[""];

}

flag=‘a‘;

};

$scope.chk= function (z,x) {//单选或者多选

if(flag==‘a‘) {//在全选的基础上操作

str = $scope.choseArr.join(‘,‘) + ‘,‘;

}

if (x == true) {//选中

str = str + z + ‘,‘;

} else {

str = str.replace(z + ‘,‘, ‘‘);//取消选中

}

$scope.choseArr=(str.substr(0,str.length-1)).split(‘,‘);

};

$scope.delete= function () {// 操作CURD

if($scope.choseArr[0]==""||$scope.choseArr.length==0){//没有选择一个的时候提示

alert("请至少选中一条数据在操作!")

return;

};

for(var i=0;i<$scope.choseArr.length;i++){

//alert($scope.choseArr[i]);

console.log($scope.choseArr[i]);//遍历选中的id

}

};

以上是 AngularJS实现全选反选功能 的全部内容, 来源链接: utcz.com/z/320648.html

回到顶部