1、精确匹配
angular的filter中过滤都是模糊过滤的,也就是只要属性中包含filter的关键字就可以被过滤出来,比如filter:1,那么属性中的10、4881、1等包含1的数字都能被过滤出来:
示例:
$scope.employees =[{id:101, name:'John', phone:'555-1276'},
{id:1012, name:'Mary', phone:'800-1233'},
{id:31013,name:'Mike', phone:'555-4321'},
{id:104,name:'Adam', phone:'555-5678'},
{id:105,name:'Julie', phone:'555-8765'},
{id:106,name:'Juliette', phone:'555-5678'}];
<table>
<tr>
<th>name</th>
<th>phone</th>
<th>ID</th>
</tr>
<tr ng-repeat="employee in employees| filter:{id:101} ">
<td class="dbclicktd">{{employee.name}}</td>
<td>{{employee.phone}}</td>
<td>{{employee.id}}</td>
</tr>
</table>
结果:
解决方案:若想精确匹配,如上要匹配出id为101的那条数据,在filter最后加上 :true 即可。
<table>
<tr>
<th>name</th>
<th>phone</th>
<th>ID</th>
</tr>
<tr ng-repeat="employee in employees| filter:{id:101} :true ">
<td class="dbclicktd">{{employee.name}}</td>
<td>{{employee.phone}}</td>
<td>{{employee.id}}</td>
</tr>
</table>
结果:
项目开发遇到的坑:一旦为精确匹配后,变量的值和类型都要完全匹配才能过滤出来。我就遇到,过滤关键字类型为字符串类型,而列表中为数字,所以就没有成功过滤。因为关键字取的后台返回的数据所以当时没注意,遇到这种情况,如果在JS中处理后台返回的数据也就是将字符串转为数字会比较麻烦且影响性能,采用这种小技巧:在字符串前面直接加上 + 号,这样就会强制将字符串类型变量转换为数字类型了。
<table>
<tr>
<th>name</th>
<th>phone</th>
<th>ID</th>
</tr>
<tr ng-repeat="employee in employees| filter:{id:'101'} ">
<td class="dbclicktd">{{employee.name}}</td>
<td>{{employee.phone}}</td>
<td>{{employee.id}}</td>
</tr>
</table>
如上:在模糊匹配时id为字符串类型是没有影响的,因为filter过滤时,做了类型转换。
但是!在精确匹配下就无法匹配出字符串类型的类型的匹配值,如下:
<table>
<tr>
<th>name</th>
<th>phone</th>
<th>ID</th>
</tr>
<tr ng-repeat="employee in employees| filter:{id:'101'} :true">
<td class="dbclicktd">{{employee.name}}</td>
<td>{{employee.phone}}</td>
<td>{{employee.id}}</td>
</tr>
</table>

这里匹配出的结果为空!
解决方案:在filter变量名前加上 + 号
<table>
<tr>
<th>name</th>
<th>phone</th>
<th>ID</th>
</tr>
<tr ng-repeat="employee in employees|filter:{id:+'101'}:true">
<td>{{employee.name}}</td>
<td>{{employee.phone}}</td>
<td>{{employee.id}}</td>
</tr>
</table>
结果
也就是说: