How to display length of filtered ng-repeat data

前端 未结 8 1149
花落未央
花落未央 2020-11-22 08:11

I have a data array which contains many objects (JSON format). The following can be assumed as the contents of this array:

var data = [
  {
    \"name\": \"         


        
相关标签:
8条回答
  • 2020-11-22 08:39

    ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.

    In your case, in may be better to apply the filter inside of your controller using the $filter service:

    function MainCtrl( $scope, filterFilter ) {
      // ...
    
      $scope.filteredData = myNormalData;
    
      $scope.$watch( 'myInputModel', function ( val ) {
        $scope.filteredData = filterFilter( myNormalData, val );
      });
    
      // ...
    }
    

    And then you use the filteredData property in your view instead. Here is a working Plunker: http://plnkr.co/edit/7c1l24rPkuKPOS5o2qtx?p=preview

    0 讨论(0)
  • Since AngularJS 1.3 you can use aliases:

    item in items | filter:x as results
    

    and somewhere:

    <span>Total {{results.length}} result(s).</span>
    

    From docs:

    You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

    For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

    0 讨论(0)
提交回复
热议问题