我正在使用带有过滤器的ng-repeat指令,如下所示:

<div ng-repeat="person in data">
</div


即显示{{data.length}}人。 (我希望将长度值传递给控制器​​)

但是我需要将过滤后的长度值传递给控制器​​,因为我基于过滤后的长度值执行相同的逻辑。

最佳答案

1.方法1

ng-repeat="item in filtered = (data | filter:filterExpr)"


将创建过滤列表。

filtered.length将显示过滤后的长度。

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);
  });

});

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

10-06 00:17