Need to understand Dependency Injection in Angular.js

后端 未结 2 707
伪装坚强ぢ
伪装坚强ぢ 2021-01-03 13:04

I am a newbie in Angular.js and came across a topic called \"Dependency Injection\". I am totally confused after reading the article.

As per the doc

2条回答
  •  梦谈多话
    2021-01-03 13:57

    I want to share of what I thought was a really great example of DI. I'm taking this example from the Angular.js documentation.

    angular.module('xmpl.service', [])
    
      .value('greeter', {
        salutation: 'Hello',
        localize: function(localization) {
          this.salutation = localization.salutation;
        },
        greet: function(name) {
          return this.salutation + ' ' + name + '!';
        }
      })
    
      .value('user', {
        load: function(name) {
          this.name = name;
        }
      });
    
    angular.module('xmpl.directive', []);
    
    angular.module('xmpl.filter', []);
    
    angular.module('xmpl', ['xmpl.service', 'xmpl.directive', 'xmpl.filter'])
    
      .run(function(greeter, user) {
        // This is effectively part of the main method initialization code
        greeter.localize({
          salutation: 'Bonjour'
        });
        user.load('World');
      })
    
      .controller('XmplController', function($scope, greeter, user){
        $scope.greeting = greeter.greet(user.name);
      });
    

    This code defines a separate module for directive, filter and service. As written in the documentation:

    Run blocks are the closest thing in Angular to the main method.

    So, the xmpl module has 3 dependencies which are injected using DI.

提交回复
热议问题