How to get parent element inside ng-include when iterating in ng-repeat recursively

后端 未结 2 1094
轻奢々
轻奢々 2021-02-02 18:17

I made a recursive ng-repeat element, and trying to manipulate things has turned into a nightmare, because I don\'t have reference to the parent I\'m iterating over.

The

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-02 18:44

    ng-repeat creates a new scope for each element.
    ng-include also creates a new scope.

    When you use ng-include together with ng-repeat, there are 2 scopes created for each element:

    • Scope created by ng-repeat for current element. This scope holds the current element in the iteration.
    • Child scope created by ng-include which inherits from ng-repeat's created scope.

    The $parent property of current scope allows you to access its parent scope.

    Essentially, scope created by ng-include is empty, when you access value and key in your node.html, it actually access the inherited values from parent scope created by ng-repeat.

    In your node.html, accessing {{value}} is actually the same as {{$parent.value}}. Therefore if you need to access the parent of the current element, you have to do one step further by accessing {{$parent.$parent.value}}

    This DEMO will clear things up:

        
    

    If you need to simplify the way to access the parent, you could try initializing the parent using onload of ng-include. Like this:

    In your top level, there is no ng-if => only 2 level deep

    In your sub levels, there is ng-if => 3 levels deep:

        

    Inside the template, you could access the parent using parent, grandparent using parent.parent and so on.

    DEMO

提交回复
热议问题