Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using Object prototype in Angular expression

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.

like image 534
d-_-b Avatar asked Feb 20 '26 02:02

d-_-b


2 Answers

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

$scope.getKeys = Object.keys;

And then in the template :

{{getKeys(obj).length}}
like image 170
Michael P. Bazos Avatar answered Feb 21 '26 17:02

Michael P. Bazos


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.

like image 39
dfsq Avatar answered Feb 21 '26 15:02

dfsq