3

How can I use Object.keys(obj).length in an angular Expression?

For example, this does not work:

{{Object.keys(obj).length}}

even though

{{obj}} prints out a JSON object.

2
  • Pretty sure you got to use use a function - pass your obj to it Commented Mar 10, 2015 at 15:59
  • Yea, i figured i'd pass it into the ng-init and use it from there. just curious why Object is out of scope or something.. Commented Mar 10, 2015 at 16:02

2 Answers 2

3

One solution is to add Object.keys function to the scope :

$scope.getKeys = Object.keys;

And then in the template :

{{getKeys(obj).length}}
Sign up to request clarification or add additional context in comments.

1 Comment

Good workaround. Out of my way, Angular.
3

just curious why Object is out of scope or something

Because Object methods are not allowed in Angular expressions. Check source code for parser if you want to see what else is disallowed.

// ...
} else if (// block Object so that we can't get hold of dangerous Object.* methods
    obj === Object) {
  throw $parseMinErr('isecobj',
      'Referencing Object in Angular expressions is disallowed! Expression: {0}',
      fullExpression);
}

What you can do instead is to expose necessary method or object to the scope explicitly using $scope object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.