Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-ng-include

Angularjs aliasing scopes


I'm stil learning Angular so forgive me if the question is nonsense

I have an object with this hierarchy:

{
    a : [...],
    b : [{
        a: [...]
    }, {
        ...
    }]
}

That is I have the same object model for direct children and indirect children of the main object. That is, the two properties named "a" have the same fields

I built a view that is managed with ng-view, and thought that could be called in the main controller and in the ng-repeat that iterates through b elements. However, I don't know how to change the scope that is passed to the view managing "a":

The main view is made in this way:

<div ng-controller="MainController as ctrl">
    <div ng-include="'subView'"/>
    <div ng-repeat="bElement in ctrl.b">
        <div ng-include="'subView'"/>
    </div>
</div>

In subView, i can access element like bElement.a because I get the same scope as the outer controller. But how to access property a of the root element?

What I would need, is to have something like ng-repeat that permits to create an alias to a property so that it can be overridden, but without the "repeat".

I tried also using ng-init in this way:

<div ng-controller="MainController as ctrl">
    <div ng-include="'subView'" ng-init="list = ctrl.a"/>
    <div ng-repeat="bElement in ctrl.b">
        <div ng-include="'subView'" ng-init="list = bElement.a"/>
    </div>
</div>

but only the second invocation works


Solution

  • Above code should work, but the only thing which I can see here missing is, you haven't closed below ng-include div correctly. So it stops browser will not consider the exact next div & the innner ng-repeat div will not get render.

    <div ng-include="'subView'" ng-init="list = ctrl.a"/>
    

    So it should be closed the div correctly, so that the next element on same will taken by browser.

    <div ng-include="'subView'" ng-init="list = ctrl.a"></div>
    

    Sample Plunkr of above issue.


    Solved working Plunkr list variable updated in child.

    Though it will work, I'm seeing some architectural threat in current implementation, because current implementation looks very tightly coupled. Any small change in requirement could lead to re-work on it. As ng-init may harm you in future. If suppose your collection is going to update in specified time of interval(at that ng-init expression will not evaluated on second time rendering of template)