欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS实现全选反选功能

程序员文章站 2022-11-23 22:00:53
angularjs是为了克服html在构建应用上的不足而设计的。html是一门很好的为静态文本展示设计的声明式语言,但要构建web应用的话它就显得乏力了。所以我做了一些工作...

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

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

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

效果:

AngularJS实现全选反选功能

<!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) 

AngularJS实现全选反选功能

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
}
};