Assigning Controllers to Angular Directives is the norm when building out components. But what if you wanted to dynamically assign a Controller to the same Directive and template? There are reasons for using this technique (though uncommon), and the undocumented
name property bound to each Directive’s definition Object can allow us to do exactly that.
Hard-coded Controller lookups
Let’s look at a “hard-coded” Directive Controller which we use everyday:
FirstCtrl which is passed into the Angular module, and then we reference it inside our Directive using
controller: 'FirstCtrl'. This is great, however we can make this Controller lookup completely dynamic very easily!
Let’s add another Controller and call it
Dynamic Controller lookups
The next step is changing the Directive to allow the Controller lookup value to be dynamic. This is done using the undocumented
name: [value] do? It allows us to pass value through an attribute into the Directive which we can use as a dynamic String for looking up Controllers in the module. The value of
name becomes the attribute we bind to the Directive. For instance our
fooDirective element will have an attribute
If assigning a Controller, we would simply declare it as an attribute:
Pretty simple, right?
It won’t work just yet, as our Directive
controller: 'FirstCtrl' is still referencing wrong. We can actually change the
'FirstCtrl' value to
'@' and it’ll work perfectly.
All together now:
Then we can add the same Directive again, passing in another Controller name as a String:
This also plays extremely nicely with the
controllerAs syntax inside our Directive’s template, we don’t need to change anything!
link function we also get the fourth argument (which I alias as
$ctrl) given to us, with the correct instance of each dynamically assigned Controller: