时间:2021-02-18 11:21:28 | 栏目:AngularJS | 点击:次
在页面中我们常常会遇到多选框,例如购物车里的商品
下面用angular来实现这一功能
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script src="js/angular.min.js"></script> </head> <body ng-app="select" ng-controller="moreSel"> 全选: <input type="checkbox" ng-checked="checks" ng-click="checks = !checks; all(checks)"> <!--track by $index去掉也可以--> <div ng-repeat="item in datas track by $index"> <input type="checkbox" ng-checked="chkItem[$index]" ng-click="ck(chkItem[$index]==undefind?false:chkItem[$index], item, $index)">{{ item }} </div> <pre>{{arr}}</pre> </body> <script> //创建模块 angular.module("select", []) //控制器 .controller("moreSel", function ($scope) { $scope.datas = ["C++","Html","Javascript"]; $scope.arr = [];//用来显示选中的内容 //用来标志每一项的状态 $scope.chkItem = []; //全选 $scope.all = function (checks) { //初始化设置状态 init(checks); //将选中的内容赋值到数组中 if(checks) { for(var i = 0; i < $scope.datas.length; i++) { $scope.arr[i] = $scope.datas[i]; } }else { $scope.arr = []; } } //点击选择 $scope.ck = function (state, item, index) { //取状态的相反值 $scope.chkItem[index] = !state; //有一个为false则全选按钮为不选中 if(!$scope.chkItem[index]){ $scope.checks = false; //取消选中,将数值从arr数组中删除掉 var num = $scope.arr.indexOf(item); $scope.arr.splice(num, 1); }else { //选中追加进去 $scope.arr.push(item); for(var i = 0; i < $scope.datas.length; i++) { //只要有一个按钮没有选中 if(!$scope.chkItem[i]){ return; } } //全部选中 $scope.checks = true; } } //初始化 var init = function (sel) { for(var i = 0; i < $scope.datas.length; i++) { //sel没有值 默认初始化false $scope.chkItem[i] = sel || false; } } }); </script> </html>