3

I'm getting started with AngularJS, and I'm trying to wrap my head around dependency injection. Specifically, I'm trying to understand the differences between DI and declaring dependencies with RequireJS.

Does DI in Angular only work for "objects" (Factories, Services, Models) which are defined on some angular.module? For example, could I depend on some external library like jQuery using DI?

In general, can the difference between dependency management in RequireJS and DI in Angular be stated like this:

RequireJS deals with loading dependencies only when they are first needed (lazy loading) and makes sure all dependencies exist before executing, whereas Angular DI allows easily changing a dependency, in runtime, as long as it's interface stays the same?

And finally, does DI always pass in instance of the dependency? A new instance every time, or a singleton? Can it pass in a "Class" definition which I can instantiate myself? For example, what if I need to pass options to the constructor?

1 Answer 1

9

Does DI in Angular only work for "objects" (Factories, Services, Models) which are defined on some angular.module?

Yes. The module is actually a wrapper of services etc.

could I depend on some external library like jQuery using DI?

Yes, we are doing it like: myModule.constant("jQuery", window.$).

A new instance every time, or a singleton?

Allways a singleton, except for the $scope. Additionally the controllers are allways instantiated anew (but still the controller function is of course a singleton).

Can it pass in a "Class" definition which I can instantiate myself?

Yes, of course. Just return the constructor function from the definition function, e.g.: (EDIT: This has to be used with factory; using service will instantiate the MyClass and use the instance for the service value)

factory("Xxx", function(dep1, dep2) {
    function MyClass() {
        ...
    }

    MyClass.prototype.method = function() ...

    return MyClass;
});

This is what you could do with RequireJS too.


As for the difference with RequireJS: One thing I can tell for sure is that RequireJS incorporates a script loader as well as a DI framework (and the optimizer too). So Require (AMD) modules have 1-1 relationship with script files. On the other hand, Angular modules and services have no required relation to files.

Other than that, they look similar to me.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.