简体   繁体   中英

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?

  • Do you have to inject directives from different files? If not, how does Angular know what directives to make available in the controller? Are they all available? Why make them all available for directives but not providers?
  • 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?

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.

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

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