Skip to content Skip to sidebar Skip to footer

Angular What Is The Best Way To Access Total Objects Within Ng-repeat Directive

Accessing thhe the length of items within a ng-repeat seems simple. {{array.length}} But when you have to iterate trough objects and you have to know the total objects then you do

Solution 1:

by creating a custom filter that return the Object.keys you can get the length of the object keys

angular.module('customfilter', []).filter('keys', function() {
  return function(obj) {
    return Object.keys(obj);
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='customfilter' ng-init="data={a:1,b:2}">
<p>the array: {{ data | keys}}</p>
  <p>the array length: {{ (data | keys).length}}</p>
</div>

Solution 2:

You don't need to define a filter for it and you can also avoid manual $watch for it by using a $scope function:

$scope.totalPersons = function() {
    return Object.keys($scope.data).length;
};

Now, simply call this method in your HTML:

<ul>
    <li ng-repeat="(key, value) in data">{{key}} - {{value}} -{{totalPersons()}}
    </li>
</ul>

In this way, Angular will self-update the count. Cheers :-)


Solution 3:

You can extend the prototype of object but that is a general solution which reflects on all objects.

Object.prototype.size = function(){
  return Object.keys(this).length
};

And then:

<li ng-repeat="(key, value) in data">{{key}} - {{value}} -{{data.size()}}

or

<ul ng-init="totalPersons=data.size()">
   <li ng-repeat="(key, value) in data">{{key}} - {{value}} -{{totalPersons}}

Post a Comment for "Angular What Is The Best Way To Access Total Objects Within Ng-repeat Directive"