How to inject dependencies to a named angular directive controller?

328 views Asked by At

If I have code similar to this question on injecting another controller to a directive:

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' 
    };
});

When I minify js, the injected dependencies of $scope and $http break, how can I explicitly define the dependencies of ParamCtrl when creating DeviceDirective to prevent uncaught injector issues with bundled js?

1

There are 1 answers

0
Wilmer SH On

I am very late to this question but I'll give it a shot. The syntax is based on John Papa's Angular style guide

First you need a way to make your controller reusable. Convert it from an anonymous function to a named function and pass it to your angular app like so:

// Named controller function
ParamCtrl function($scope, $http) {
   this.doStuff
}

// Bind it to your app
angular.module('paramApp').controller('ParamCtrl', ['$scope', '$http', ParamCtrl );

// While we are at it, do the same with your directive
DeviceDirective function (controlerParam) {    
    return { 
        ...
        controller: controlerParam
    } 
}

// Bind it to your app
angular.module('deviceApp', ['ParamCtrl', DeviceDirective]);

However, if you meant to pass the controller's scope to your directive refer to fiznool's post