I want to iterate through myObject
in an AngularJS template
This does not work :
<ul ng-if="Object.keys(myObject).length">
<li ng-repeat="(key, val) in myObject">
Value at key {{ key }} is: {{ val }}
</li>
</ul>
Nothing shows up, I suspect because $scope.Object
is not defined.
Instead, I did this :
In the controller/directive :
$scope.sizeOf = function(obj) {
return Object.keys(obj).length;
};
In the template :
<ul ng-if="sizeOf(myObject)">
<li ng-repeat="(key, val) in myObject">
Value at key {{ key }} is: {{ val }}
</li>
</ul>
I do not like this solution because of the duplication of this function in every single controller or directive $scope
.
Do you see any cleaner solution?
Thanks !
AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.
var keys = Object. keys(objInstance); var len = keys. length; Where len is your "length."
You can use Object
in ngIf
directive everywhere. Just put its reference to the root scope:
app.run(function($rootScope) {
$rootScope.Object = Object;
});
It will also be available in isolated scopes such as in directives.
UPD. In recent version of Angular you can't reference Object
in expressions anymore. In this case you will need to reference methods individually:
app.run(function($rootScope) {
$rootScope.keys = Object.keys;
});
and then use this function:
ng-if="keys(myObject).length"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With