11

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.

4
  • Can you fix your object structure? Right now it's not valid. Commented Feb 25, 2015 at 10:29
  • @dfsq sorry, I've edited. Commented Feb 25, 2015 at 10:32
  • 1
    Well it's still not valid javascript syntax. Looks like you indeed need an array: $scope.items = [{"name": "Jim", "age" : 25}, {"name": "Eric", "age" : 25}]. Or if this is an object then: $scope.items = {0: {"name": "Jim", "age" : 25}, 1: {"name": "Eric", "age" : 25}}. Commented Feb 25, 2015 at 10:34
  • Yes the second one. Basically a map (key, value). Commented Feb 25, 2015 at 10:37

2 Answers 2

15

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) }}
Sign up to request clarification or add additional context in comments.

4 Comments

But I need it on the page
It seems that this is the only way, since there is not function to call the map size.
I agree with your approach, but @Magini your model for array is very estrange... You should to try a default array using [ ... ].
@JoaozitoPolo I use this as (key, value) map and not array that's why :)
4

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.