Alibabaev
Alibabaev

Reputation: 71

How to count items inarray by attribute in Angular JS?

In my contrller.js I have array 'arr'

Like This :

$scope.arr = [
   {block: 0},
   {block: 1},
   {block: 1},
]

I want to count items with block : 1 but not using ng-repeat? I tried:

{{arr.lenght | filter:block == '1'}}

Upvotes: 2

Views: 7561

Answers (2)

Jorge Casariego
Jorge Casariego

Reputation: 22212

This is an example using filter

Html

<div ng-controller="MyCtrl">
    Amount is {{(arr|amount)}}

</div>

Javascript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {

    $scope.arr = [
       {block: 0},
       {block: 1},
       {block: 1},
    ]
}

 myApp.filter("amount", function(){
    return function(array){     
        var amount = 0;
        for(var i = 0; i < array.length; i++){ 
            if(array[i].block == 1)
                amount+= 1;
        }

        return amount;
    };
});

Here a jsFiddle of the example

Upvotes: 1

Tong Shen
Tong Shen

Reputation: 1369

Try this:

{{ ( arr | filter: { block: 1 } ).length }}

arr | filter: { block: 1 } will return an array that matches your condition.

Upvotes: 5

Related Questions