我想突出显示创建表的ng-repeat下的搜索文本。 我找到了一个过滤器作为我的解决方案,但它不适用于表格。
任何人都可以指出我错误的地方让它发挥作用。
<body ng-app="Demo">
<h1>Hello Plunker!</h1>
<div class="container" ng-controller="Demo">
<input type="text" placeholder="Search" ng-model="search">
<table>
<thead>
<th>Some</th>
<th>MyName</th>
</thead>
<tbody>
<tr ng-repeat="item in data | filter:search"
>
<td>
<td>{{item.title}}</td>
<td>{{item.name}}</td>
</td>
</tr>
</tbody>
<!-- with filter -->
</table>
</div>
<script>
angular.module('Demo', [])
.controller('Demo', function($scope) {
$scope.data = [
{ title: "Bad",name:'kaushik' },
{ title: "Good",name:'1kaushik' },
{ title: "Great",name:'2kaushik' },
{ title: "Cool" ,name:'3kaushik'},
{ title: "Excellent",name:'4kaushik' },
{ title: "Awesome",name:'5kaushik' },
{ title: "Horrible",name:'6kaushik' },
]
})
.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)
}
})
</script>
</body>
This is working copy of the & demo the same thing I wants is with table.
答案 0 :(得分:2)
您未应用highlight
过滤器,并且您还拥有嵌套的<td>
元素。试试这个:
<tr ng-repeat="item in data | filter:search">
<td ng-bind-html="item.title | highlight:search></td>
<td ng-bind-html="item.name | highlight:search"></td>
</tr>
angular.module('Demo', [])
.controller('Demo', function($scope) {
$scope.data = [{
title: "Bad",
name: 'kaushik'
},
{
title: "Good",
name: '1kaushik'
},
{
title: "Great",
name: '2kaushik'
},
{
title: "Cool",
name: '3kaushik'
},
{
title: "Excellent",
name: '4kaushik'
},
{
title: "Awesome",
name: '5kaushik'
},
{
title: "Horrible",
name: '6kaushik'
},
]
})
.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)
}
});
&#13;
.highlighted {
background-color: yellow;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<body ng-app="Demo">
<h1>Hello Plunker!</h1>
<div class="container" ng-controller="Demo">
<input type="text" placeholder="Search" ng-model="search">
<table>
<thead>
<th>Some</th>
<th>MyName</th>
</thead>
<tbody>
<tr ng-repeat="item in data | filter:search">
<td>
<td ng-bind-html="item.title | highlight:search"></td>
<td ng-bind-html="item.name | highlight:search"></td>
</td>
</tr>
</tbody>
<!-- with filter -->
</table>
</div>
<script>
</script>
</body>
&#13;