繁体   English   中英

使用 AngularJS 突出显示字符串中的单词

[英]Highlighting a word within a string with AngularJS

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

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

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

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

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

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

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

这是一个plnkr 示例

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;
    };
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM