我正在使用带有过滤器的ng-repeat指令,如下所示:
<div ng-repeat="person in data">
</div
即显示{{data.length}}
人。 (我希望将长度值传递给控制器)
但我需要将过滤后的长度值传递给控制器,因为我根据过滤的长度值执行相同的逻辑。
答案 0 :(得分:2)
1.Method 1
ng-repeat="item in filtered = (data | filter:filterExpr)"
会创建已过滤的列表。
filtered.length
将显示已过滤的长度。
2.Method 2
使用$watch
检测过滤后的长度。
$scope.length = $scope.data.length;
$scope.$watch("search", function(query) {
$scope.length = $filter("filter")($scope.data, query).length;
});
示例强>
var app = angular.module('angularjs-starter', [])
app.controller('MainCtrl', function($scope, $filter) {
$scope.data = [{
"name": "Martin",
"age": 21
}, {
"name": "Peter",
"age": 26
}, {
"name": "Arun",
"age": 25
}, {
"name": "Maxwell",
"age": 22
}];
$scope.counted = $scope.data.length;
$scope.$watch("search", function(query) {
$scope.filteredData = $filter("filter")($scope.data, query);
});
});
&#13;
<html ng-app="angularjs-starter">
<head lang="en">
<meta charset="utf-8">
<title>Demo</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<link rel="stylesheet" href="style.css">
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input ng-model="search" type="text">
<br>Showing {{data.length}} Persons;
<br>Filtered {{filteredData.length}}
<ul>
<li ng-repeat="person in filteredData">
{{person.name}}
</li>
</ul>
</body>
<script>
</script>
</html>
&#13;