marked-down
marked-down

Reputation: 10408

How to access controller's scope from a twice or thrice nested ng-repeat scope?

I don't really think I can elucidate much more than I already have in the title, it's a fairly self-descriptive question.

Say I have this structure:

<div ng-repeat="type in types">
  <div ng-repeat="subtype in type.subtypes">
    <div ng-repeat="item in subtype.items">
        <span>How to access Controller scope here?</span>
    </div>
  </div>
</div>

Inside the span, how can I access the original scope on the controller?

In Knockout, you can do $parents[i] where i is however many scopes you want to step back up in. I haven't seen a reference to that being possible with Angular.

Do I really have to call $parent.$parent.$parent?

Upvotes: 0

Views: 143

Answers (1)

Josh Beam
Josh Beam

Reputation: 19772

Do I really have to call $parent.$parent.$parent?

No:

<div ng-repeat="type in types">
  <div ng-repeat="subtype in type.subtypes">
    <div ng-repeat="item in subtype.items">
        {{type}} {{subtype}} {{item}}
    </div>
  </div>
</div>

They all inherit from the top-level scope.

If you're worried about conflicting namespaces, checkout the controllerAs syntax:

<div ng-controller="ParentCtrl as parent">
    {{parent.property}}
  <div ng-controller="ChildCtrl as child">
    {{parent.property}}
    {{child.property}}
  </div>
</div>

What happens if you have conflicting properties in different scopes? Which gets picked?

The one at the lowest level.

Upvotes: 2

Related Questions