I want to dynamically specify a controller based on a config that we load. Something like this:
<div ng-controller="{{config.controllerNameString}}>
...
</div>
How do I do this in angular? I thought this would be very easy, but I can seem to find a way of doing this.
I'm using it in ng-repeat, so this is improved code for loops and sub objects:
Template:
Directive:
Personally the 2 current solutions here didn't work for me, as the name of the controller would not be known when first compiling the element but later on during another digest cycle. Therefore I ended up using:
What you want to do is have another directive run before anything else is called, get the controller name from some model remove the new directive and add the
ng-controller
directive, then re-compile the element.That looks like this:
Then you could use it in your template, like so:
with a controller like this:
There's probably a way of interpolating the value (
$interpolate
) of thedynamic-ctrl
instead of parsing it ($parse
), but I couldn't get it to work for some reason.