Reputation: 672
I have:
<div ng-controller="fooControlle as fc">
<div ng-repeat"fooObj in fc.fooCollection">
<div ng-controller="barController as bc" ng-init="bc.init()">
bc output here
</div>
</div>
</div>
I need to access fooObj from bc.init().
I tried:
ng-init="bc.init(fooObj)"
but fooObj is unknown.
By using $parent from my init function, I will see my collection but will not know which one is my current item.
Any thoughts? Thanks in advance.
Upvotes: 0
Views: 22
Reputation: 672
Thank you guys for your answers. Pankaj, you showed me the way :)
It was dead simple in the end, with two options:
ng-init="bc.init($parent.fooObj)"
or
var init = function(){
var foo = $parent.fooObj
}
Second way is clearly cleaner as there is no added value to send a value through a parameter when you can access it the same way from within the function.
The key here is that I misunderstood what the $parent was here. I thought it was the parent controller context when it was the ng-repeat current iteration context.
Thanks for your assistance.
Upvotes: 0
Reputation: 342
personally the easiet would be to create a directive for the barController part and pass in the fooObj as a parameter to the directive
app.directive("foo", [function(){
return {
restrict: "E",
controller: "barController",
templateUrl: "",
scope: {
bar: "="
}
};
}]);
Then your html could be
<div ng-controller="fooControlle as fc">
<div ng-repeat"fooObj in fc.fooCollection">
<foo bar="fooObj"></foo>
</div>
</div>
Upvotes: 0
Reputation: 136154
I would suggest you should pass the $index
with your $parent.fooObj
that will give you track on which element your there
<div ng-controller="fooControlle as fc">
<div ng-repeat"fooObj in fc.fooCollection">
<div ng-controller="barController as bc" ng-init="bc.init($parent.fooObj, $parent.$index)">
bc output here
</div>
</div>
</div>
For making it more better your fooObj should have an unique value that could differentiate that it, like you should have something like fooObj = {id: 1, .....}
Upvotes: 1