Adam Zerner
Adam Zerner

Reputation: 19208

Do Angular directives need to be dependency injected into controllers?

I know that when you have the directive and controller in the same file, you don't. Ie

.directive('example', function() {
})
.controller('MainCtrl', function($scope) {
  // could use the example directive in the corresponding html
});

But I've always thought that when the directive is in a different file, you do need to inject it into the controller. Like this:

example.directive.js

.directive('example', function() {
})

main.controller.js

.controller('MainCtrl', function($scope, example) {
});

See this plnkr. In it, the directive and controller are in two different files, and the directive doesn't work.

Note: In my app, I used the angular-fullstack generator to create the directive, and the directive is available in the controller without me having to inject it. Is this because of the generator?

Anyway, when I try to inject the directive into the controller, I get an error saying unknown provider: exampleProvider.

What's going on here?

Upvotes: 1

Views: 1303

Answers (2)

Peter Lyons
Peter Lyons

Reputation: 146014

Do you have to inject directives from different files?

It's not based on files, it's based on angular module names. Sometimes directives from one module can be defined in the same file, sometimes different files, but both ways can work provided the module names are declared correctly and the module containing the controller depends properly on the module containing the directive.

When you do this:

angular.module('myapp' ['mod1', 'mod2']);

Then any controller defined on the myapp module can use any directive from myapp, mod1, and mod2 (as well as the built-in directives in angular core).

What happens when the directive and controller are in the same file to make it so you don't need to inject the directive into the controller?

I think you are confusing the same file with the same module. In this case if both the directive and the controller are defined on the same application (in the same file, but that's not essential), then the controller can use the directive.


Looking at your plnkr above, all is well EXCEPT you forgot one basic ingredient - your index.html doesn't actually load the directive.js file, so add this:

    <script src="directive.js"></script>

Then the directive works correctly.

Upvotes: 3

Josef Joe Samanek
Josef Joe Samanek

Reputation: 1704

Directives are not injected. They are automatically available in the module in which you define them.

Upvotes: 1

Related Questions