Reputation: 2741
Basically, I have a controller, "PageCtrl", which pulls in a list of data via a service. The data is saved inside the PageCtrl. All works fine - so far so good.
Now my issue: for each object of the data inside the PageCtrl, I use ng-repeat to display each data just fetched.
In each of the ng-repeats, I use ng-include to get the correct template, depending of which data is in each object (basically the data is a list of elements that is to be displayed on the page. Each element has it's own controller.
As ng-include creates a newscope, all the created child scopes/controllers have access to the data, as it is located in the $parent controller - PageCtrl.
All works fine, except that each created controller in ng-repeat/ng-include needs to know which object in list of data in the parent, it needs to use to display.
Basically, in my ng-repeat, I would like to use the $index and pass it to the controller included in the ng-include. But I cannot do it! If I use ng-init, that code inside ng-init will be executed on the parent scope, ie. my original PageCtrl.
How can I, without the use of directives, pass information to the controller so that it knows which of the data-objects in its parent it should use?
Here is the code that loops over the data in MainCtrl:
<div ng-repeat="element in elements" >
<ng-include src=" GetTemplateFromElement(element.type) " ng-init=" SetElementNo($index); "></ng-include>
</div>
In the snippet, I call GetTemplateFromElement on the MainCtrl which returns the view to include. In the included view I refer which controller should do the work. I try to use $index to tell the included controller which index in the data it should use. But ofcourse the code is executed in MainCtrl scope. Example of a view:
<div ng-controller="ElementDocumentCtrl">
<div ng-bind-html-unsafe="element.document_content"></div>
</div>
In the snippet, "element.document_content" is on the scope of ElementDocumentCtrl, which pulls the data from its parent, PageCtrl.
How can I tell the directives included which index in the data-list in PageCtrl (it's parent controller) it should pick up?
Please don't tell me I need to make them all directives :)
Thanks, guys.
Upvotes: 2
Views: 3809
Reputation: 5450
Maybe Im not understanding your question completely, but from the docs, $index, $first, $middle and $last are all exposed on the local scope of the ng-repeat children.
Ive put in a plunker to demonstrate this. The ChildCtrl accesses the $index from the parent to get the index of which element in the parent it is accessing.
Upvotes: 3