oikonomiyaki
oikonomiyaki

Reputation: 7951

How to inject a controller to a directive in another module

I have a module 'paramApp' with controller 'ParamCtrl':

var app = angular.app('paramApp', []);

app.controller('ParamCtrl', ['$scope', '$http', function($scope, $http) {
   .
   .
   .
}]);

I have another module 'deviceApp' with directive 'DeviceDirective':

var app2 = angular.app('deviceApp', []);

app2.directive('DeviceDirective', function() {

    return {
        .
        .
        .
        controller: // I want to reference ParamCtrl here
        controllerAs: param
    };

});

I read somewhere that I need to use angular.injector (or $injector) to inject the controller, but I'm not so sure how to use it. My attempts to use the injector didn't work.

Is this approach right? Do I need to declare 'paramApp' in 'deviceApp' declaration like this,

var app2 = angular.app('deviceApp', ['paramApp']);

Please help on how to use injector in the directive controller to reference another module's controller.

Upvotes: 0

Views: 3665

Answers (1)

rom99
rom99

Reputation: 799

I think you mean angular.module('paramApp', []) and angular.module('deviceApp', [])? Your approach of declaring the dependency seems right though. I would recommend not assigning all your modules to variables so you aren't polluting the global scope. For your example you could try:

angular.module('paramApp', []);

angular.module('paramApp').controller('ParamCtrl', ['$scope', '$http', function($scope, $http) {
   .
   .
   .
}]);

angular.module('deviceApp', ['paramApp']);
angular.module('deviceApp').directive('DeviceDirective', function () {    
    return { 
    .
    .
    .
    controller: 'ParamCtrl' 
    };
});

Upvotes: 3

Related Questions