在ng-repeat AngularJS中满足ng-if后,计算迭代次数并显示计数一次

时间:2016-08-06 02:38:21

标签: javascript angularjs

我有一行代码:

<div ng-repeat="ticket in scope.tickets track by $index" ng-if="ticket.film_id == film.id"> {{$index}} Ticket(s)</div>

目前这显示了索引并重复了div元素,但我希望每个都有计数,我只想显示每个ng的最后一个计数 - 如果它最终看起来像这样:

4 Ticket(s)
2 Tickets(s)
3 Tickets(s)

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:0)

嗯,我从您的问题中得到的是,您正在尝试计算内部ngRepeat中的对象,因此您可以使用 native filter

您只需使用filtered表达式对as项的结果进行归因,如下所示:

<div ng-repeat="ticket in tickets | filter: { film_id: film.id }: true as filtered track by $index">

这是简单 演示

&#13;
&#13;
(function() {
  'use strict';

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];

  function MainCtrl($scope) {
    $scope.films = [];
    $scope.tickets = [  
       {  
          "film_id":"id 1",
          "name":"ticket 1"
       },
       {  
          "film_id":"id 1",
          "name":"ticket 2"
       },
       {  
          "film_id":"id 1",
          "name":"ticket 3"
       },
       {  
          "film_id":"id 1",
          "name":"ticket 4"
       },
       {  
          "film_id":"id 2",
          "name":"ticket 5"
       },
       {  
          "film_id":"id 2",
          "name":"ticket 6"
       },
       {  
          "film_id":"id 3",
          "name":"ticket 7"
       },
       {  
          "film_id":"id 3",
          "name":"ticket 8"
       },
       {  
          "film_id":"id 3",
          "name":"ticket 9"
       }
    ];
    
    // 4 Films with id = 1, 3 films with id = 3, 2 films with id = 2

    function loadFilms(max) {
      var i = 0;
      while(i++ < max) {
        $scope.films.push({
          "id": "id " + i,
          "name": "film " + i
        })
      }
    }

    loadFilms(10);
  }
})();
&#13;
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl">
  <div ng-repeat="film in films track by $index">
    <span ng-bind="film.id"></span>
    <div ng-repeat="ticket in tickets | filter: { film_id: film.id }: true as filtered track by $index">
    </div>
    <!-- to show 0 tickets just remove the ng-if check below -->
    <span ng-if="filtered.length" ng-bind-template="{{filtered.length}} Ticket(s)"></span>
  </div>
</body>

</html>
&#13;
&#13;
&#13;