0

I'm displaying a string in the UI, the string is held in a $scope variable.

<p>{{stringValue}}</p>

I want to highlight a word in that string after I click on a button. I tried:

$scope.go = function () {
 $scope.stringValue = $scope.stringValue.replace("word", "<span class='highlight'>" + "word" + "</span>");
}

But the <span> tags show up in the view now.

2 Answers 2

1

Try using the ng-bind-html directive.

<p ng-bind-html="stringValue"></p>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was it!
1

Here's a plnkr example

HTML

<div><label>The string: </label><input type="text" ng-model="stringValue"></div>
<p ng-bind-html="stringValue | highlight:highlightStr"></p>
<input type="text" ng-model="willHighlightStr">
<button type="button" ng-click="doHighlight()">highlight</button>

JavaScript

    var app = angular.module('plunker', ['ngSanitize']);

  app.controller('MainCtrl', function($scope) {
    $scope.stringValue = 'Hello World';
    $scope.willHighlightStr = '';
    $scope.highlightStr = '';
    $scope.doHighlight = function() {
      $scope.highlightStr = $scope.willHighlightStr;
    }
  });

  app.filter('highlight', function($sce, $injector, $log) {
    var isSanitizePresent;
    isSanitizePresent = $injector.has('$sanitize');

    function escapeRegexp(queryToEscape) {
      // Regex: capture the whole query string and replace it with the string that will be used to match
      // the results, for example if the capture is "a" the result will be \a
      return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
    }

    function containsHtml(matchItem) {
      return /<.*>/g.test(matchItem);
    }

    return function(matchItem, query) {
      if (!isSanitizePresent && containsHtml(matchItem)) {
        $log.warn('Unsafe use of typeahead please use ngSanitize'); // Warn the user about the danger
      }
      matchItem = query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem; // Replaces the capture string with a the same string inside of a "strong" tag
      if (!isSanitizePresent) {
        matchItem = $sce.trustAsHtml(matchItem); // If $sanitize is not present we pack the string in a $sce object for the ng-bind-html directive
      }
      return matchItem;
    };
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.