可以使用AngularJS的过滤器和控制器来计算数组中匹配项的出现次数。下面是一个示例代码:
HTML模板:
- {{item}}
匹配的出现次数:{{getMatchCount()}}
JavaScript代码:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.items = ['apple', 'banana', 'orange', 'apple', 'grapefruit', 'apple'];
$scope.getMatchCount = function() {
var count = 0;
var filteredItems = $filter('filter')($scope.items, $scope.searchText);
angular.forEach(filteredItems, function(item) {
if (item === $scope.searchText) {
count++;
}
});
return count;
};
});
在这个示例中,我们首先定义了一个数组items
,它包含了一些水果名称。然后我们使用ng-repeat指令来循环遍历数组中的每个元素,并使用过滤器filter:searchText
来过滤出与搜索文本匹配的项进行显示。
在控制器中,我们定义了一个函数getMatchCount
来计算匹配项的出现次数。首先,我们使用$filter
服务来过滤数组,获取与搜索文本匹配的项。然后,我们使用angular.forEach
函数遍历过滤后的数组,统计与搜索文本完全匹配的项的个数,最后返回计数。
最后,在模板中使用{{getMatchCount()}}
来显示匹配的出现次数。
请注意,为了使用$filter
服务,我们需要在控制器中注入$filter
依赖。