How to display length of filtered ng-repeat data

前端 未结 8 1331
花落未央
花落未央 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:30

    For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.

    Assuming your list of people is in data variable and you filter people using query model, the following code will work for you:

    Number of visible people: {{(data|filter:query).length}}

    Total number of people: {{data.length}}

    • {{data.length}} - prints total number of people
    • {{(data|filter:query).length}} - prints filtered number of people

    Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.

    New Feature in Angular 1.3

    AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.

    Number of visible people: {{results.length}}

    The alias expression will prevent multiple filter execution issue.

    I hope that will help.

提交回复
热议问题