简体   繁体   English

AngularJS尝试查找使用limitTo的已过滤数组的总长度

[英]AngularJS Trying to find the total length of a filtered array that uses limitTo

So I'm trying to get the total length of a filtered array in AngularJS after I've used LimitTo to keep the app from displaying more than a certain amount of elements at a time. 所以我试图在使用LimitTo来保持应用程序一次显示超过一定数量的元素之后,在AngularJS中获取已过滤数组的总长度。 The code is as follows: 代码如下:

<span>Results: {{filtered.length}}</span>
<li ng-repeat = "element in filtered = (array | filter:selectedTag | limitTo:load.number)">

I'm expecting about 150 total results but I'm keeping it limited to displaying 25 at a time. 我预计总共会有大约150个结果,但我仍然限制它一次显示25个。 I want the Results to show the total length of the filtered array rather than just the limited version. 我希望结果显示已过滤数组的总长度,而不仅仅是限制版本。 Is there angular code to be able to get that without running the filter again? 是否有角度代码能够在不再运行过滤器的情况下获得该代码?

You're allowed to create a new variable on-the-fly , right inside the ng-repeat expression. 您可以在ng-repeat表达式内即时创建新变量。 This new variable can hold a reference to filtered results and it can be used outside of ng-repeat : 这个新变量可以保存对过滤结果的引用,它可以在ng-repeat之外使用:

PLUNKER DEMO PLUNKER DEMO

<div>Total: {{array.length}}</div>
<div>Filtered: {{filtered.length}}</div>

<ul>
  <li ng-repeat="element in (filtered = (array | filter:selectedTag)) | limitTo:load.number">
      {{element}}
  </li>
</ul>

This way the filtering loop will run only once. 这样过滤循环只运行一次。

Unfortunately there is no way to avoid running the filter twice without writing some javascript to assign the result of the filter to a variable. 不幸的是,如果没有编写一些javascript来将过滤器的结果分配给变量,就无法避免运行过滤器两次。

So, one solution would be to run the selectedTag filter in your controller whenever your array changes, store that locally and use it in your view. 因此,一种解决方案是在数组更改时在控制器中运行selectedTag过滤器,将其存储在本地并在视图中使用它。

Add this code to your controller: 将此代码添加到您的控制器:

.controler($scope, $filter) {
    // Existing code
    $scope.array = ...
    $scope.selectedTag = ...

    // New code
    $scope.filteredArray = [];

    $scope.$watchCollection('array', function (array) {
        $scope.filteredArray = $filter('filter')(array, $scope.selectedTag);
    });
}

And in your view: 在你看来:

<span>Results: {{filteredArray.length}}</span>
<li ng-repeat = "element in filteredArray | limitTo:load.number">

References - http://docs.angularjs.org/api/ng.filter:filter 参考文献 - http://docs.angularjs.org/api/ng.filter:filter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM