1

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 don't have a Angular thing for it.

What I did now is count the total properties and store it in a variable.

$scope.totalPersons =  Object.keys($scope.data).length;

But when items are added to the object the totalPersons is not updated so I changed this so the value will be updated.

$scope.$watch( $scope.data, function (newValue, oldValue) {
    $scope.totalPersons = Object.keys($scope.data).length;
});

But is there a better way to access the total objects in your template?

<ul>
    <li ng-repeat="(key, value) in data">
        {{key}} - {{value}}  {{totalPersons}}
    </li>
</ul>
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
chriscrossweb
  • 338
  • 1
  • 5
  • 23

3 Answers3

2

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>
Zamboney
  • 2,002
  • 12
  • 22
0

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 :-)

Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
-1

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}}
kidwon
  • 4,448
  • 5
  • 28
  • 45