Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check object size in AngularJS template, doing it wrong?

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 !

like image 205
Pandaiolo Avatar asked Mar 27 '14 14:03

Pandaiolo


People also ask

What is ngRepeat?

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.

How do I find the length of a object in angular 10?

var keys = Object. keys(objInstance); var len = keys. length; Where len is your "length."


1 Answers

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"
like image 64
dfsq Avatar answered Sep 20 '22 13:09

dfsq