angularjs自定义过滤器demo示例
qq328691560 人气:0本文实例讲述了angularjs自定义过滤器demo。分享给大家供大家参考,具体如下:
这个基于angularjs的过滤器是最近做的"信息管理学院实验室预约"项目中的一个小功能。
以下为数据:
$scope['classes']=[{id:1,name:"H503",capacity:40,software:"photoshop,金蝶,AI",freeTime:"周一1-2-3,周五1-2-3,周一5-6,"}, {id:2,name:"H504",capacity:50,software:"chrome,金蝶,office," ,freeTime:"周二1-2-3,周三3-4,周一5-6,"}, {id:3,name:"H505",capacity:60,software:"chrome,LOL,office," ,freeTime:"周二1-2-3,周三3-4,周四7-8,"} ];
具体功能:
分别在两个select选择星期和课次,列表会即时根据条件更新。
完整代码:
<!DOCTYPE html> <html ng-app="myApp" > <head> <meta charset="utf-8"> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-controller="myCtrl"> <select ng-model="day"> <option selected="">周一</option> <option>周二</option> <option>周三</option> <option>周四</option> <option>周五</option> </select> <select ng-model="order"> <option selected="">1-2</option> <option>1-2-3</option> <option>3-4</option> <option>1-2-3-4</option> <option>5-6</option> <option>7-8</option> </select> <ul> <li ng-repeat="class in classes | myFiter:day:order"> <span>{{class.id}}</span> <span>{{class.name}}</span> <span>{{class.capacity}}</span> <span>{{class.software}}</span> </li> </ul> </select> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { //假数据 $scope['classes']=[{id:1,name:"H503",capacity:40,software:"photoshop,金蝶,AI",freeTime:"周一1-2-3,周五1-2-3,周一5-6,"}, {id:2,name:"H504",capacity:50,software:"chrome,金蝶,office," ,freeTime:"周二1-2-3,周三3-4,周一5-6,"}, {id:3,name:"H505",capacity:60,software:"chrome,LOL,office," ,freeTime:"周二1-2-3,周三3-4,周四7-8,"} ]; //select的默认值 $scope.order="1-2"; $scope.day="周一"; }); //自定义过滤器 app.filter('myFiter',function() { return function(input,day,order) { var time=day+order; var output=[]; for(var i=0;i<input.length;i++) { var n=input[i].freeTime.indexOf(time); // console.log(n); // console.log(input[i].freeTime.charAt(n+time.length)); if(n!=-1)//如果能找到 { if(input[i].freeTime.charAt(n+time.length)==',') //这样做是为了防止1-2与1-2-3是一样的结果 output.push(input[i]); } } return output; } }) </script> </body> </html>
运行效果:
总结:filter可以理解为一个带参数的函数,它把一个对象进行一些处理,然后把处理后的对象返回。不过我认为以上的这个算法有待优化。
希望本文所述对大家AngularJS程序设计有所帮助。
加载全部内容