简体   繁体   中英

How to inject dependencies to a named angular directive controller?

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM