AngularJS中过滤器filter的精确匹配

博客主要围绕Angular的filter过滤器展开。介绍了其默认模糊过滤的特点,若要精确匹配需在filter最后加 :true。还指出精确匹配时变量值和类型要完全一致,遇到类型不匹配问题,可在字符串前加 + 号强制转换类型,以解决过滤失败的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>

结果

也就是说:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值