0

When I do a search in my application, I want to wrap the matching characters in the results with bold tags so you can see the matches.

So the results view looks like:

<ul class="search-results ng-hide" ng-show="(results | filter: filterQuery).length > 0">
    <li ng-repeat="result in results | filter:filterQuery">
        <h3><a ui-sref="{{result.state}}">{{result.name}}</a></h3>
        <p>{{result.snippet}}</p>
    </li>
</ul>

And the controller:

myApp.controller('SearchCtrl', function($rootScope, $scope, $state, Result, $location, $filter) {

    $scope.query = ($state.includes('search') ? $location.search()['q'] : '');
    $scope.filterQuery = ($state.includes('search') ? $location.search()['q'] : '');

    $scope.results = [];

    $scope.queryChanged = function () {
        $scope.filterQuery = $scope.query;
        if($scope.query){
            $state.go('search', {'q': $scope.query} );
        } else {
            $location.search('q', null);
        }
    }

    if($scope.query){
        $scope.results = Result.query();
    } else {
        $location.search('q', null);
    }

});

So I need to wrap tags around the result.name and result.snippet when it matches the filterQuery.

Something like (bits of this were copied from a PHP version I've done in the past, hence the mismatched syntax):

var keys = $scope.filterQuery.split(" ");
result.snippet.replace('/('.implode('|', keys) .')/iu', '<b>\0</b>');

But where would this go?

Cameron
  • 27,963
  • 100
  • 281
  • 483

2 Answers2

0

Create a search-result directive to wrap each search result, where name needs to be set as bold:

<search-result result="result" name="name" ></search-result>

With the following template:

directive.template: 'prefix text' + '<B>' + attrs.name + </B> + ' suffix text';
ps0604
  • 1,227
  • 23
  • 133
  • 330
0

There's a few ways you could do this, mostly using filters.

You could write your own filter, that would take the string in the search, find it in the content that you are searching, and then add the tags around it and send it back.

Or, you can use one of the many plugins out there that does this.

Heres a question that talks about it

Angular UI Highlight

Community
  • 1
  • 1
ribsies
  • 1,218
  • 2
  • 10
  • 16