Search code examples
javascriptangularjshighlighting

Highlighting with angularjs and $sce


Please see the following picture:

enter image description here

It's good.

Now, please see following picture:

enter image description here

It's not good for me.

I need to be highlighted first following statement:

statement : as

Then the following statement:

statement : dad

And they both are highlighted. How to do it?

js code :

tableService.highlight = function (text, search) {
                if (!search) {
                    return $sce.trustAsHtml(text);
                }
                var trustAsHtml = $sce.trustAsHtml(text.replace(new RegExp(search, 'gi'), '<span class="highlightedText">$&</span>'));

                return trustAsHtml;
            };

cshtml code :

<td ng-hide="$index == tableService.choiseDeleteRecord ||$index==tableService.choiseUpdateRecord">
                <span ng-bind-html="tableService.highlight(newsCategory.NameFa, pagerService.search)"> {{newsCategory.NameFa}}</span>
            </td>
            <td class="direction-left" ng-hide="$index == tableService.choiseDeleteRecord ||$index==tableService.choiseUpdateRecord">
                <span ng-bind-html="tableService.highlight(newsCategory.NameFa, pagerService.search)"> {{newsCategory.NameEn}}</span>
            </td>

Solution

  • I've tried and I succeeded. But my code might not be optimal.

    Please share if you have a better way

    enter image description here

    js code :

      tableService.highlight = function (text, search) {
            if (!search) {
                return $sce.trustAsHtml(text);
            }
            var splitSearch = search.split(' ');
            $.each(splitSearch, function (index, value) {
                text = replaceAll(value, '#####$&~~~~~', text);
            });
            text = replaceAll('#####', '<span class="highlightedText">', text);
            text = replaceAll('~~~~~', '</span>', text);
            var trustAsHtml = $sce.trustAsHtml(text);
            return trustAsHtml;
        };