Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a dynamic controller in an AngularJS directive?

I have a directive that has a dynamic template, now I want the directive to have the ability to use different controllers. Is it possible to dynamically assign a controller to a directive? If possible, would that be the same "ctrlr" then passed to the link function?

.directive('myDirective',['$compile',function($compile){
    return {
        restrict: 'AE',
        replace: true,
        transclude: true,
        scope: {},
        templateUrl: function(el,attrs){
            return (angular.isDefined(attrs.template)) ? attrs.template : '/tmpls/default';
        },
        link : function(scope,el,attrs,ctrlr,transFn){
            [... Do Stuff Here ...]
        },
        controller: [ DYNAMIC CONTROLLER ASSIGNMENT?? ]
    };
}]);
like image 876
m.e.conroy Avatar asked Mar 19 '26 16:03

m.e.conroy


1 Answers

While I didn't find the corresponding documentation for it in the official API, you can dynamically pass in the name of the controller you want to use by utilizing the "name" attribute in conjunction with providing the "controller" attribute with a value that uses the similar syntax you'd use for an isolate scope.

Using your sample code, assuming a controller called "myController":

HTML:

<my-directive ctrlr="myController"></my-directive>

JS:

.directive('myDirective',['$compile',function($compile){
    return {
        restrict: 'AE',
        replace: true,
        transclude: true,
        scope: {},
        templateUrl: function(el,attrs){
            return (angular.isDefined(attrs.template)) ? attrs.template : '/tmpls/default';
        },
        link : function(scope,el,attrs,ctrlr,transFn){
            [... Do Stuff Here ...]
        },
        controller: '@',
        name: 'ctrlr'
    };
}]);
like image 181
RobM Avatar answered Mar 22 '26 08:03

RobM