用角度突出显示字符串中的单词

时间:2016-09-03 03:30:08

标签: javascript angularjs

我在UI中显示一个字符串,字符串保存在$ scope变量中。

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

我想点击按钮后突出显示该字符串中的单词。我试过了:

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

<span>标签现在显示在视图中

2 个答案:

答案 0 :(得分:1)

尝试使用ng-bind-html指令。

<p ng-bind-html="stringValue"></p>

答案 1 :(得分:1)

这里是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;
    };
  });