Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

angularjs - Can't retrieve the injector from angular

I've got this app with two modules:

angular.module('components', []).directive('foo', function () { return {};});
angular.module('gaad', ['components']);

There is a bunch of directives associated with this modules which I'm not including here. The application works fine. However when I'm trying to retrieve injector for module gaad:

var injector = angular.injector(['gaad', 'components']); //called after 'gaad' module initialization

the error is thrown:

Uncaught Error: Unknown provider: $compileProvider from components 

The application is quite big right now and I have no idea where should I look for bugs. So my question is: What could be the reason for my problems?

EDIT: I was able to replicate my problem: http://jsfiddle.net/selbh/ehmnt/11/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Before answering the question we need to note that there is only one injector instance per application and not per module. In this sense it is not possible to retrieve an injector per module. Of course if we take the top-level module, it represents the whole application. In this sense, an application and top-level module seem equivalent. It might seem like a subtle difference but it is important to understand in order to fully and properly answer this question.

Next, from what I can understand you would like to retrieve the $injector and not create a new instance of it. The thing is that the angular.injector will create a new $injector instance for modules (an app) specified as arguments. Here the main AngularJS module (ng) must be specified explicitly. So, in this code example:

var injector = angular.injector(['gaad', 'components']);

you were trying to create a new injector from components defined in 'gaad' and 'components' modules and obviously $compileProvider is not defined in your custom modules. Adding the ng module to the list would "solve" the problem by creating a new injector - something that you probably don't want to happen.

To actually retrieve an injector instance associated to a running application we can use 2 methods:

Here is the jsFiddle showing 2 methods of the injector retrieval: http://jsfiddle.net/xaQzb/

Please also note that using $injector directly is not very common scenario outside of unit testing. It might be useful thought for retrieving AngularJS services from outside of AngularJS world. More info here: Call Angular JS from legacy code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...