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() {
returnfunction(obj) {
returnObject.keys(obj);
};
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-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() {
returnObject.keys($scope.data).length;
};
Now, simply call this method in your HTML:
<ul><ling-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(){
returnObject.keys(this).length
};
And then:
<li ng-repeat="(key, value) in data">{{key}} - {{value}} -{{data.size()}}
or
<ulng-init="totalPersons=data.size()"><ling-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"