Supriya Pandey Supriya Pandey - 1 year ago 81
AngularJS Question

Dependency Injection with Exact Example using Angular Javascript

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.

Answer Source

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:

  1. We can create it internally to the dependent.
  2. We can look it up or refer to it as a global variable.
  3. 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); }
function($scope, greeter) {
$scope.sayHello = function() {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download