Reputation: 7123
I have $scope.data
that is already displaying to the screen using ng-repeat
, I have a input where user can search from $scope.data
, So i created filter if user search text matched with $scope.data
highlight that text ,its not throwing any exception but also not highlighting the text, I am fairly new to angularjs filters help will be much appreciated. Thanks in advance.
ctrl.js
$scope.data = ["Lorem Ipsum is simply dummy text", "Lorem Ipsum is simply dummy text"];
main.html
<div class="row search-input-margin">
<div class="col-md-12 form-group">
<div class="col-md-3">
<label for="search">Search Logs:</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" id="search" ng-model="vm.searchLog">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<ul style="list-style: none;">
<li ng-repeat="message in data track by $index"><span><strong>Log:</strong></span><span>{{message}}</span></li>
</ul>
</div>
<div>
<ul>
<!-- filter code -->
<div ng-repeat="item in data | filter:vm.searchLog"
ng-bind-html="item | highlight:vm.searchLog">
</div>
</ul>
</div>
</div>
filter.js
angular.module('App').filter('highlight', function($sce) {
return function(text, phrase) {
if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
'<span class="highlighted">$1</span>')
return $sce.trustAsHtml(text)
}
});
Upvotes: 2
Views: 2451
Reputation: 25807
You are missing style for the .highlighted
class
var app = angular.module("sa", []);
app.controller("FooController", function($scope) {
$scope.data = ["Lorem Ipsum is simply dummy text", "Lorem Ipsum is simply dummy"];
});
app.filter('highlight', function($sce) {
return function(text, phrase) {
if (phrase) text = text.replace(new RegExp('(' + phrase + ')', 'gi'),
'<span class="highlighted">$1</span>')
return $sce.trustAsHtml(text)
}
});
.highlighted {
font-weight: bold
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<div ng-app="sa" ng-controller="FooController as vm">
<div class="row search-input-margin">
<div class="col-md-12 form-group">
<div class="col-md-3">
<label for="search">Search Logs:</label>
</div>
<div class="col-md-9">
<input type="text" class="form-control" id="search" ng-model="vm.searchLog">
</div>
</div>
</div>
<ul>
<!-- filter code -->
<li ng-repeat="item in data | filter: vm.searchLog" ng-bind-html="item | highlight:vm.searchLog">
</li>
</ul>
</div>
Upvotes: 4
Reputation: 23642
<div ng-repeat="item in data | filter:vm.searchLog"
ng-bind-html-unsafe="item | highlight:vm.searchLog">
</div>
Why don't you use ng-bind-html-unsafe
here? and if you are using ng-bind-html
are you loading angular-sanitize.min.js
A more detailed link here: AngularJS : Insert HTML into view
Upvotes: 0