I am New to learn a Angular Javascript. Can anyone gave me the knowledge of Dependency Injection with Its Demo Example. So That I did learn from there. No Good and clear link I have found from Googling.
-
1It is impossible you could not find any good and clear explanation on google for subjects like dependency injection and angular. – Pawan Nogariya May 23 '16 at 12:00
-
I've found a great one. [Angular Docs](https://docs.angularjs.org/guide/di) – Matt Lishman May 23 '16 at 12:08
1 Answers
Dependency injection is a design pattern that allows for the removal of hard-coded dependencies, thus making it possible to remove or change them at run time.
In general, there are only three ways an object can get a hold of its dependencies:
- We can create it internally to the dependent.
- We can look it up or refer to it as a global variable.
- We can pass it in where it’s needed.
With dependency injection, we’re tackling the third way.We dont follow the first 2 ways because a good programmer never dirty the global scope and it will be difficult for the isolation of the code.
This ability to modify dependencies at run time allows us to create isolated environments that are ideal for testing. We can replace real objects in production environments with mocked ones for testing environments.
For instance,let us consider this simple app that declares a single module and a single controller, like so:
angular.module('myApp', [])
.factory('greeter', function() {
return {
greet: function(msg) { alert(msg); }
}
})
.controller('MyController',
function($scope, greeter) {
$scope.sayHello = function() {
greeter.greet("Hello!");
};
});
At run time, when Angular instantiates the instance of our module, it looks up the greeter and simply passes it in naturally.
Nowhere in the above example did we describe how to find the greeter; it simply works, as the injector takes care of finding and loading it for us.
For further reference please visit Angularjs Modularization and Dependency injection which can help you get a better understanding.

- 464
- 7
- 20
-
what is the difference between service and factory? Can You please describe me with example? – Supriya Pandey May 23 '16 at 12:13
-
I hope http://stackoverflow.com/questions/23074875/angularjs-factory-and-service can help you. – Denny John May 23 '16 at 12:16