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.


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!");
    };
    });
    链接地址: http://www.djcxy.com/p/77990.html

    上一篇: angularJS $范围变量

    下一篇: 使用Angular Javascript的精确示例的依赖注入