Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does angularjs need IoC/DI?

Following this question

https://stackoverflow.com/a/2465052/41948

So Python doesn't need IoC/DI because it's dynamic scripting language already.

Javascript is also a dynamic scripting langauge, why does angularjs need DI then?

Is it because JSON <-> DOM is static? Could someone give me a minimal example?

like image 420
est Avatar asked Sep 25 '13 08:09

est


People also ask

Why is the need of DI in angular?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

Does AngularJS use dependency injection?

Dependency Injection is pervasive throughout AngularJS. You can use it when defining components or when providing run and config blocks for a module.

What is IoC in angular?

This idea of moving the responsibility of creating concrete instances of dependencies to something else is called Inversion of Control, or IoC. The specific design pattern for implementing IoC above is called Dependency Injection, we injected the dependencies of EmailSender in the constructor.

How does AngularJS dependency injection work?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.


1 Answers

Dependency Injection (DI) in Angular wasn't a necessary decision. Most other JavaScript frameworks don't have it built in. (Although look at Marionette, a framework built on top of Backbone.js... it includes an optional DI layer). Angular.js comes with a set of architectural opinions that help you separate your code. It was built in as a design decision, not a necessity.

The biggest reason it is necessary for YOU to use DI in Angular is because that is the way Angular works. The angular team could have decided to use an Asynchronous Module Definition (AMD) library like Require.js. Instead they chose a DI pattern and baked it in for convenience.

The link you posted suggests that DI might be an anti-pattern in dynamic languages. I disagree with that. I'd just say that DI is less necessary in dynamic languages. In the case of Angular, however, it works well. They allow you to compose your system of parts and inject only what you need, when you need it. When you look at the way other frameworks do it, they (often) just namespace their Model/View/Controller/Template/Router parts in the global space (Like App.Models.Person in Backbone.js).

I find DI in Angular to be like "When in Rome, do as the Romans do". Embrace the architectural decision. It feels good.

like image 125
Brian Genisio Avatar answered Oct 04 '22 22:10

Brian Genisio