Reputation: 7083
searchStr
is user input search keyword , once i rendered response from server i want to highlight user input searchStr
so user can see what is being searched and compare if its part of response. So below code is highlighting whole string response from server in my case i just want to highlight searched string that will be part of response.
Lets assume i have string
info|<n/a>|[routes.event] ########## Message added to processing queue ########## e63637db-aa33-4aed-b5b0-51a0764dc7f1 { workerId: 3, pid: 33029 }
and i want to highlight e63637db-aa33-4aed-b5b0-51a0764dc7f1
_id that will be searchStr
main.html
<tr ng-repeat="item in showMessages | filter:searchStr" >
<td >{{item.filename}}</td>
<td class="serverResults" ng-bind-html="item.value | trusted">{{item.value}}</td>
</tr>
ctrl.js
$scope.$on('displaySearchResults',function(e,data){
$scope.searchStr = data.searchStr;
$scope.showMessages = data.messageObj;
})
filters.js
angular.module('App').filter('trusted', ['$sce', function ($sce) {
return function(text,phrase) {
if (phrase) text = text.replace(new RegExp('('+phrase+')', 'gi'),
'<span class="highlighted">$1</span>');
var content = text.toString()
console.log('Content',content);
var data = content.replace(/[|&;$%@"<>()+,]/g, "");
return $sce.trustAsResourceUrl(data);
};
}]);
Upvotes: 1
Views: 168
Reputation: 7194
Here is a working sample to show how you might accomplish the highlighting. It is contrived because I'm just creating an array with a single item, but it illustrates the approach. You want to apply your replacement of reserved characters first because if you apply that after you have inserted the highlighted <span>
the <
and >
characters will be stripped by your replacement regex.
angular.module('app', [])
.controller('ctrl', function($scope) {
$scope.showMessages = [{
value: 'info|<n/a>|[routes.event] ########## Message added to processing queue ########## e63637db-aa33-4aed-b5b0-51a0764dc7f1 { workerId: 3, pid: 33029 }'
}];
$scope.searchStr = 'e63637db-aa33-4aed-b5b0-51a0764dc7f1';
})
.filter('trusted', function($sce) {
return function(text, phrase) {
if (phrase) {
var data = text.replace(/[|&;$%@"<>()+,]/g, "");
data = data.replace(new RegExp('(' + phrase + ')', 'gi'),
'<span class="highlighted">$1</span>');
return $sce.trustAsHtml(data);
}
text = text.replace(/[|&;$%@"<>()+,]/g, "");
return $sce.trustAsHtml(text);
};
});
.highlighted {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div>Search: <input type="text" ng-model="searchStr" /></div>
<div>
<table>
<tr ng-repeat="item in showMessages | filter:searchStr">
<td>{{item.filename}}</td>
<td class="serverResults" ng-bind-html="item.value | trusted:searchStr"></td>
</tr>
</table>
</div>
</div>
Upvotes: 1