twsaef
twsaef

Reputation: 2121

How do I use array syntax for dependency injection with a directive controller?

I want to be able to specify the controller of my directive with an inline function, but I also want to use ng-strict-di. What syntax is required to do this?

(function(){
    angular.module("myAngularModule")
    .directive("myDirective", function(){
        return {
            restrict: 'E',
            templateUrl: "templates/my-template.html",
            link: function ($scope, element, attrs) {
                // ...
            },
            // This causes an ng-strict-di exception because I'm using implicit annotation for the dependencies - what is the correct syntax?
            controller: function($scope, myService) { 
                // ...
            }
        };
    })
    // This syntax is fine
    .controller("myWorkingController",["$scope","myService", function($scope, myService){ 
        // ...
    }]);
});

Upvotes: 0

Views: 1025

Answers (2)

twsaef
twsaef

Reputation: 2121

Just because the controller is anonymous doesn't meant the syntax changes. Pass an array like you would any other controller assignment. Angular will understand.

controller: ["$scope","myService", function($scope, myService){
    // ...
}]

Upvotes: 3

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

Inject the service in to your directive as, its something like injecting into the controller,

.directive("myDirective", function(myService){

and remove it from the controller.

.directive("myDirective", function(myService){
    return {
        restrict: 'E',
        templateUrl: "templates/my-template.html",
        link: function ($scope, element, attrs) {
            // ...
        },

        controller: function($scope) { 
            // ...
        }
    };
})

then myService can be access in the controller of the directive.

Upvotes: 2

Related Questions