我正在构建一个 AngularJS 应用程序。我有这个数组:
$scope.products = [
{name: 'cake (just it!)'},
{name: 'orange cake'},
{name: 'cheesecake'}
];
然后我使用 ng-repeat 来显示它。
<li ng-repeat="product in products | filter : { name : word }">
{{ $product.name }}
</li>
我想添加一个过滤器来搜索短语中每个单词的开头,所以如果我这样做:
$scope.word = 'ca';
它将返回以下数组:
$scope.products = [
{name: 'cake (just it!)'},
{name: 'orange cake'}
];
最佳答案
您可以使用如下所述的自定义过滤器来完成此操作
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.products = [{
name: 'cake (just it!)'
}, {
name: 'orange cake'
}, {
name: 'cheesecake'
}, {
name: 'cheese'
}, {
name: 'cheeseca ca'
}];
}
]);
app.filter("nameFilter", function() {
return function(names, contains) {
return names.filter(function(obj) {
var expString = '(\\w*\\s|^)' + contains + '';
var exp = new RegExp(expString, "g");
if (exp.test(obj.name))
return name;
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<ul>
<li ng-repeat="product in products | nameFilter : 'ca' ">
{{product.name}}
</li>
</ul>
</div>
</div>
关于javascript - 短语内单词的 Angular 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066734/