0

Is there an easy way to read a property defined in one of the parents scopes from a controller? Just like Angular does in templates, as the docs explains:

When Angular evaluates {{name}}, it first looks at the scope associated with the given element for the name property. If no such property is found, it searches the parent scope and so on until the root scope is reached. In JavaScript this behavior is known as prototypical inheritance, and child scopes prototypically inherit from their parents.

But this behaviour is not applied inside controllers, if you write $scope.name it just looks in the current scope.

Javier Marín
  • 2,166
  • 3
  • 21
  • 40

1 Answers1

0

Very easily done: $scope.$parent.name

See angular documentation at the bottom for reference.

Edit

Scope properties from any parent in the hierachical tree can be retrieved by naming the controllers as posted in this SO answer: angularjs Access parent scope from child controller and accessing them by the named parent.

Community
  • 1
  • 1
Gecko
  • 1,333
  • 1
  • 14
  • 26
  • I know that workaround, but it doesn't work if the property is in an upper level, I would have to iterate over '$parent' property until find it. That's why I'm asking for a easier way. – Javier Marín Sep 03 '14 at 11:34
  • I think that naming controllers is an ugly solution, in OO programming you don't need to indicate the parent class name in order to access it inherited properties – Javier Marín Sep 03 '14 at 11:55
  • JavaScript isn't exactly an OO programming language, nor is Angular. – Gecko Sep 03 '14 at 11:58
  • That's true, but it's confusing to have a different behaviour between templates and controllers in this subject – Javier Marín Sep 03 '14 at 12:06
  • I can certainly relate to that! – Gecko Sep 03 '14 at 12:11