gpt4 book ai didi

javascript - AngularJS:在 ng-repeat 中修改值

转载 作者:行者123 更新时间:2023-11-30 00:33:17 24 4
gpt4 key购买 nike

我在 Angular 中有一个简单的表格:

<table>
<tr ng-repeat="row in $data">
<td>{{row.name}}</td>
<td>{{row.surname}}</td>
</tr>
</table>

这会呈现这样的东西:

<table>
<tr>
<td>Johnathan</td>
<td>Smith</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</table>

但我有一个重新加载表格的动态搜索功能,我需要像这样在结果中突出显示搜索字符串(搜索词是“John”):

<table>
<tr>
<td><span class="red">John</span>athan</td>
<td>Smith</td>
</tr>
</table>

现在我希望这样的事情能奏效:

<table>
<tr ng-repeat="row in $data">
<td>{{myFunction(row.name)}}</td>
<td>{{row.surname}}</td>
</tr>
</table>

但事实并非如此。有什么方法可以使它起作用吗?

更新:已解决,@loan 提出的解决方案适用于这种情况。

最佳答案

正如您将在下面的示例中看到的,您可以执行类似的操作。

Example

在您现有的循环中,您可以按如下方式添加自定义过滤器:

<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>

在您的 JavaScript 文件中,您可以创建自定义过滤器:

(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"
}];
}
]);

})();

如果您愿意,可以用您的值替换过滤器中的 html:

<strong>$&</strong>

<span class="red">$&</span>

关于javascript - AngularJS:在 ng-repeat 中修改值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28346861/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com