AngularJS:过滤器和结果的加粗部分 [英] AngularJS : filter and bold part of the result

查看:146
本文介绍了AngularJS:过滤器和结果的加粗部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有过滤,像这样的列表:

I have a list filtered like this:

ng-repeat="item in items | filter:query | limitTo:10"

和一个搜索输入

ng-model="search.name"

它的工作原理,但我想提出在结果查询部分大胆的。

It works but I would like to make the query part in the results bold.

例如:

query = zza

结果:


  • 李*的 ZZA 的*

  • PI *的 ZZA 的*

  • ABC *的 ZZA 的* DEF

  • Li*zza*
  • Pi*zza*
  • Abc*zza*def

推荐答案

您可以作出这样的改变基于搜索字符串输入自己的自定义过滤器:

You can make your own custom filter that alters the input based on the search string :

angular.module('app').filter('searchfilter', function() {
    return function (input, query) {
        var r = RegExp('('+ query + ')', 'g');
        return input.replace(r, '<span class="super-class">$1</span>');
    }
});

这工作,但过滤器返回的HTML,所以你需要告诉角度看待结果为HTML。为了做到这一点,你需要包括 ngSanitize 作为一个模块依赖并插入 NG-绑定-HTML 的结果。结果
下面是一个完整的演示:

This works, but the filter returns html, so you will need to tell angular to treat the result as html. In order to do this, you need to include ngSanitize as a module dependency and insert the result with ng-bind-html.
Here's a complete demo :

<div ng-app="app">
  <div ng-controller="Ctrl">
      <input ng-model="search" placeholder="search a fruit" />
      <ul>
          <li ng-repeat="fruit in fruits| filter:search | limitTo:10" ng-bind-html="fruit | searchfilter:search" ></li>
      </ul>
  </div>
</div>

和角部分:

angular
    .module('app', ['ngSanitize'])
    .controller('Ctrl', function($scope){
        $scope.fruits = 'apple orange banana pineaple grape plumb strawberry lemon lime'.split(' ');
    })
    .filter('searchfilter', function() {
        return function (input, query) {
            return input.replace(RegExp('('+ query + ')', 'g'), '<span class="super-class">$1</span>');           
        }
    });

下面的在线演示: http://jsfiddle.net/gion_13/ZDWdH/2/

这篇关于AngularJS:过滤器和结果的加粗部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆