All we need is an easy explanation of the problem, so here it is.
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.
How to solve :
I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.
Method 1
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) }}
Method 2
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>
Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0