Check object size in AngularJS template, doing it wrong?

angularjs, angularjs-scope, javascript, object

Solution

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"

Problem

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 !

Original source