在下才疏学浅,不足之处,还望多多指教。
直接上代码
<!DOCTYPE html> <html lang="en" ng-app="indexApp"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../js/angular.js"></script> <style> select{ width:150px; vertical-align:middle; } p{ display: inline-block; cursor: pointer; } </style> </head> <body ng-controller="indexCtrl"> <select ng-change="changeOne(oneData,first)" ng-model="oneData"> <option ng-repeat="item in first" value="{{item.id}}">{{item.name}}</option> </select> <select ng-change="changeTwo()" ng-model="twoData" multiple="multiple" size="10"> <option ng-repeat="item in next" value="{{item.id}}">{{item.name}}</option> </select> <p> <span ng-click="addLast(twoData,next)">-></span><br> <span ng-click="delLast(lastData,last)"><-</span> </p> <select ng-model="lastData" size="10" multiple="multiple"> <option ng-repeat="item in last track by $index" value="{{item.id}}">{{item.name}}</option> </select> <script> angular.module(‘indexApp‘,[]) .controller(‘indexCtrl‘,function($scope){ $scope.first =[ { id:1, name:‘前端‘, child:[ {id:1,name:‘CSS3‘}, {id:2,name:‘HTML‘}, {id:3,name:‘js‘}, {id:4,name:‘angular‘}, {id:5,name:‘bootstrap‘} ] }, { id:2, name:‘后端‘, child:[ {id:6,name:‘java‘}, {id:7,name:‘php‘}, {id:8,name:‘node‘} ] } ]; $scope.changeOne = function(oneData,first){ angular.forEach(first,function(i,j){ if(oneData == i.id){ $scope.next = i.child; } }) }; var boxLast=[]; $scope.addLast = function(twoData,next){ //添加 next.forEach(function(i,j){ if(parseInt(twoData) == parseInt(i.id)){ boxLast.push(i) } }); //排重 var a ={},b=[],c=[]; for(var i =0;i<boxLast.length;i++){ if( !a [boxLast[i].id] ){ a [boxLast[i].id]=true; b.push(boxLast[i]); }else{ c.push(boxLast[i].name); } } if(c.length>0){ alert(c+‘已添加‘); } boxLast = b; $scope.last = b; }; $scope.delLast = function(lastData,last){ last.forEach(function(i,j){ if(parseInt(lastData) == parseInt(i.id)){ $scope.last.splice(j,1); //删除从 左往右的 第n个 数组内容,删除一个 } }) }; }); </script> </body> </html>
执行效果如下:
页面比较简陋,但足以说明问题。
我们需要注意的有以下几点:
1. angular.forEach的使用(可以看下在下对forEach的拙见)
2. arr[10].splice(5,1) 意思是:删除数组的第五个元素
时间: 2024-10-18 02:11:59