Reputation: 12111
I have a simple table in Angular:
<table>
<tr ng-repeat="row in $data">
<td>{{row.name}}</td>
<td>{{row.surname}}</td>
</tr>
</table>
that would render something like this:
<table>
<tr>
<td>Johnathan</td>
<td>Smith</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</table>
but I have a dynamic search function that reloads the table and I need to highlight the search string in results like so (the search word is "John"):
<table>
<tr>
<td><span class="red">John</span>athan</td>
<td>Smith</td>
</tr>
</table>
now I hoped that something like this would work:
<table>
<tr ng-repeat="row in $data">
<td>{{myFunction(row.name)}}</td>
<td>{{row.surname}}</td>
</tr>
</table>
but it doesn't. Any way to make this work?
UPDATE: Solved, solution proposed by @loan works in this case.
Upvotes: 2
Views: 714
Reputation: 2200
As you'll see in the example below, you can do something similar to this.
In your existing loop you can add the custom filter as follows:
<body ng-controller="TestController">
<h1>Hello Plunker!</h1>
<input type="text" ng-model="query" />
<ul>
<li ng-repeat="item in data | filter:query">
<!-- use the custom filter to highlight your queried data -->
<span ng-bind-html="item.name | highlight:query"></span>
</li>
</ul>
</body>
In your JavaScript file you can create the custom filter:
(function() {
'use strict';
angular.module("app", []);
//to produce trusted html you should inject the $sce service
angular.module("app").filter('highlight', ['$sce', function($sce) {
function escapeRegexp(queryToEscape) {
return queryToEscape.replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
}
return function(matchItem, query) {
return $sce.trustAsHtml(query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '<strong>$&</strong>') : matchItem);
};
}]);
angular.module("app")
.controller('TestController', ['$scope',
function($scope) {
$scope.query = ""; //your scope variable that holds the query
//the dummy data source
$scope.data = [{
name: "foo"
},{
name: "bar"
},
{
name: "foo bar"
}];
}
]);
})();
if you want you can replace the html in the filter with your values:
<strong>$&</strong>
to
<span class="red">$&</span>
Upvotes: 1
Reputation: 30118
You can use angular-ui's highlight module. You can simply use it like this:
HTML
<div>
<input type="text" ng-model="searchText" placeholder="Enter search text" />
</div>
<input type="checkbox" ng-model="caseSensitive" /> Case Sensitive?
<table>
<tbody>
<tr ng-repeat="row in $data">
<td ng-bind-html="row.name | highlight:searchText:caseSensitive"></td>
<td>{{row.surname}}</td>
</tr>
</tbody>
</table>
You can download it via bower, instructions are provided in their github page.
Note: Add angular's ngSanitize to avoid an $sce
unsafe error.
Upvotes: 0