mark search string dynamically using angular.js

前端 未结 4 2132
北荒
北荒 2021-02-08 07:22

How can I mark my search pattern dynamically in my html?
Example:

\"SearchExample\"

I\'m using angular

相关标签:
4条回答
  • 2021-02-08 07:47

    Angular UI is a great choice. You can also do it with filter like: http://embed.plnkr.co/XbCsxmfrgmdtOAeBZPUp/preview

    The essence is as commented by @Hylianpuffball, dynamically create styled 'span' tags for the matches.

    .filter('highlight', function($sce) {
      return function(text, phrase) {
        if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
          '<span class="highlighted">$1</span>')
    
        return $sce.trustAsHtml(text)
      }
    })
    

    And use it like:

    <li ng-repeat="item in data | filter:search.title"
        ng-bind-html="item.title | highlight:search.title">
    </li>
    
    0 讨论(0)
  • 2021-02-08 07:51

    Just in case that someone (like me a moment ago) needs this for angular2:

    highlight-pipe.ts:

    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({name: 'highlightPipe'})
    export class HighlightPipe implements PipeTransform{
    
      transform(text:string, filter:string) : any{
        if(filter){
          text = text.replace(new RegExp('('+filter+')', 'gi'), '<span class="highlighted">$1</span>');
        }
        return text;
      }
    }
    

    and use it like this:

    at top of file:

    import {HighlightPipe} from './highlight-pipe';
    

    in template where 'yourText' is the original text and 'filter' is the part you want to highlight:

    <div [innerHTML]="yourText | highlightPipe: filter"/>
    

    in component:

    pipes: [HighlightPipe]
    

    EDIT: I updated it for RC 4 and created a plunker for testing: http://plnkr.co/edit/SeNsuwFUUqZIHllP9nT0?p=preview

    0 讨论(0)
  • 2021-02-08 08:05

    Inspired by @tungd's answer but valid for multiple search terms.

    .filter('highlight', function($sce) {
      return function(text, phrase) {
        if (phrase){
            phrases = phrase.split(" ");
            for(i=0;i<phrases.length;i++)
                text = text.replace(new RegExp('('+phrases[i]+')', 'gi'),'~~~~~$1%%%%%')
    
            text = text.replace(new RegExp('('+'~~~~~'+')', 'gi'),'<span class="bold greenTxt">');
            text = text.replace(new RegExp('('+'%%%%%'+')', 'gi'),'</span>')      
        } 
        return $sce.trustAsHtml(text)
      }
    });
    

    PS: One can always limit the input to be in non-special chars for this to be 100% bullet-proof.

    0 讨论(0)
  • 2021-02-08 08:14

    Try Angular UI

    They have a highlight directive. You can use it as a reference to make your own (or just use it directly).

    0 讨论(0)
提交回复
热议问题