2016-09-03 7 views
0

UIに文字列を表示していますが、その文字列は$ scope変数に保持されています。文字列内の単語を角で強調表示

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

ボタンをクリックした後、その文字列内の単語をハイライトしたいとします。私が試した:

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

しかし<span>タグはng-bind-htmlディレクティブを使用してみてください今

答えて

1

ビューに表示されます。

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

おかげだ、それはそれでした! – bvais

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; 
    }; 
    }); 
関連する問題