AngularJS: dynamically assign controller from ng-repeat

jacob picture jacob · Dec 19, 2012 · Viewed 21.4k times · Source

I'm trying to dynamically assign a controller for included template like so:

<section ng-repeat="panel in panels">
    <div ng-include="'path/to/file.html'" ng-controller="{{panel}}"></div>
</section>

But Angular complains that {{panel}} is undefined.

I'm guessing that {{panel}} isn't defined yet (because I can echo out {{panel}} inside the template).

I've seen plenty of examples of people setting ng-controller equal to a variable like so: ng-controller="template.ctrlr". But, without creating a duplicate concurrant loop, I can't figure out how to have the value of {{panel}} available when ng-controller needs it.

P.S. I also tried setting ng-controller="{{panel}}" in my template (thinking it must have resolved by then), but no dice.

Answer

SET picture SET · Dec 19, 2012

Your problem is that ng-controller should point to controller itself, not just string with controller's name.

So you might want to define $scope.sidepanels as array with pointers to controllers, something like this, maybe:

$scope.sidepanels = [Alerts, Subscriptions];

Here is the working example on js fiddle http://jsfiddle.net/ADukg/1559/

However, i find very weird all this situation when you might want to set up controllers in ngRepeat.