AngularJS通过编写自定义过滤器自定义搜索数据
发布时间:2020-12-17 07:50:20 所属栏目:安全 来源:网络整理
导读:假设我使用ng-repeat以表格格式显示以下数据. div class="form-group" label Search/label input type="text" ng-model="search" class="form-control" placeholder="Search" /divtable class="table table-striped table-hover" thead tr thId/th thFirst N
假设我使用ng-repeat以表格格式显示以下数据.
<div class="form-group"> <label >Search</label> <input type="text" ng-model="search" class="form-control" placeholder="Search"> </div> <table class="table table-striped table-hover"> <thead> <tr> <th>Id</th> <th>First Name</th> <th>Last Name</th> <th>Hobby</th> </tr> </thead> <tbody> <tr ng-repeat="user in users|filter:search"> <td>{{user.id}}</td> <td>{{user.first_name}}</td> <td>{{user.last_name}}</td> <td>{{user.hobby}}</td> </tr> </tbody> </table> 以上代码取自http://code.ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/ 这样我们就可以搜索了.无论用户在搜索文本框中写什么,都会根据该过滤器生成数据,但我的要求有点不同. 我将有一个下拉列表,其中将填充所有字段名称,用户将选择字段名称并将值放入文本框中,并且将在该特定字段名称上搜索数据,而不是整个结果集.我怎么能实现它. 寻求指导.
这样的东西,改编自Angular文档的过滤器将起作用.
HTML <label>Search In: <select ng-model="ctrl.searchField"> <option value="_id">ID</option> <option value="name">Name</option> <option value="phone">Phone #</option> <option value="dob">Birthday</option> </select> <label>Search For: <input ng-model="ctrl.searchText"></label> <table id="searchTextResults"> <tr> <th>ID</th> <th>Name</th> <th>Phone</th> <th>Birthday</th> </tr> <tr ng-repeat="friend in ctrl.friends | filter:ctrl.filterList"> <td>{{friend._id}}</td> <td>{{friend.name}}</td> <td>{{friend.phone}}</td> <th>{{friend.dob.toDateString()}}</th> </tr> </table> JavaScript的 angular.module("filterApp",[]).controller("filterDemo",filterDemo) function filterDemo() { let vm = this; vm.searchField = "" vm.searchText = "" vm.friends = [{ _id: 12323,name: 'Will',phone: '555-1276',dob: new Date(1990,00,20) },{ _id: 34645764576,name: 'Mike',phone: '555-4321',dob: new Date(1967,01,02) },{ _id: 6565656795,name: 'Toni',phone: '555-5678',05,21) },{ _id: 2565656,name: 'Leilani',phone: '808-BIG-WAVE',dob: new Date(2007,01) },{ _id: 67567567,name: 'Julie',phone: '555-8765',dob: new Date(1991,12,{ _id: 477676767,name: 'Juliette',name: 'Mary',phone: '800-BIG-MARY',01) }] vm.filterList = filterList function filterList(row) { if (vm.searchField && vm.searchText) { let propVal = row[vm.searchField] if (propVal) { return propVal.toString().toUpperCase().indexOf(vm.searchText.toUpperCase()) > -1; } else { return false; } } return true; }; } 这是一个有效的代码:http://codepen.io/anon/pen/yOjdJV?editors=1010 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读