Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count map size in AngularJS

Tags:

angularjs

I have a map with key values as follows

$scope.items = {
  {
    0={"name": "Jim", "age" : 25}
  },
  {
    1={"name": "Eric", "age" : 25}
  }
};

if it was an array to count the size I with do:

<div ng-repeat="item in items>
</div>

and have the size {{items.length}}

In case of a map I with iterate items as follows:

<div ng-repeat="(id, item) in items">
</div>

but how to establish the size?

Any help is appreciated.

like image 779
mzereba Avatar asked Feb 25 '15 10:02

mzereba


2 Answers

One approach is to calculate number of keys in the object using Object.keys:

$scope.itemsLength = Object.keys($scope.items).length;

you can also define a helper function:

$scope.getLength = function(obj) {
    return Object.keys(obj).length;
}

and use it in template:

{{ getLength(items) }}
like image 67
dfsq Avatar answered Oct 25 '22 04:10

dfsq


I suggest to use a filter for this, which can be used across the application:

angular.module('filters').filter('objectKeysLength', [function() {
    return function(items) {
        return Object.keys(items).length;
    };
}]);

Then use it:

{{ items | objectKeysLength }}

or

<div ng-if="(items | objectKeysLength) > 0" >
    ...content...
</div>
like image 39
jjmontes Avatar answered Oct 25 '22 06:10

jjmontes