1

私は最近angularjsを使い始めました。しかし、モジュールの概念は私を混乱させます。

angular チュートリアルの 1 つに、次のコードがあります。

'use strict';

/* Services */

var phonecatServices = angular.module('phonecatServices', ['ngResource']);

//this line's added by me
phonecatServices.constant('SomeConstant', 123);

phonecatServices.factory('Phone', ['$resource',
  function($resource){
    return $resource('phones/:phoneId.json', {}, {
      query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
  }]);

angularjs は、はるかにクリーンな nodejs と同様の方法でモジュールを定義できるのに、constant や factory などのヘルパー関数を必要とするのはなぜですか? このアプローチにはどのような利点があるのか​​ 混乱しています。

var $resource = require('$resource');

var SomeConstant = 123;

var Phone = $resource('phones/:phoneId.json', {}, {
        query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
    });
};

exports.SomeConstant = SomeConstant;
exports.Phone = Phone;
4

1 に答える 1

0

答えは、Angular の依存性注入を中心にしているようです。

APIが言うように、モジュールを作成/登録または取得するためのグローバルな手段であると考えangular.moduleてください。モジュールは、登録されているモジュール名のリストを取得する関数である がブートストラップ時に見つけることができるように、この方法で作成する必要があります。$injector

関数を「ヘルパー」とは見なしませんfactoryが、実際にはサービスの作成方法をAngular jsの依存性注入に指定する方法です。または、依存性注入ガイドで説明されているように、サービスの作成方法を $injector に「教えています」:

// Provide the wiring information in a module
angular.module('myModule', []).

  // Teach the injector how to build a 'greeter'
  // Notice that greeter itself is dependent on '$window'
  factory('greeter', function($window) {
    // This is a factory function, and is responsible for 
    // creating the 'greet' service.
    return {
      greet: function(text) {
        $window.alert(text);
      }
    };
  });

// New injector is created from the module. 
// (This is usually done automatically by angular bootstrap)
var injector = angular.injector(['myModule', 'ng']);

// Request any dependency from the injector
var greeter = injector.get('greeter'); 

このガイドでは、ここではインジェクターがモジュールから直接作成されていることも思い出させてくれますが、通常は angular のブートストラッパーがそれを処理してくれます。

つまり、要するに、angular.moduleAngular にモジュールを解決する方法を伝え (これは を介し​​て行われます$injector)、factory必要なときにモジュールを作成する方法を angular に伝えます。対照的に、Node のモジュールはファイルと 1 対 1 のマッピングを持ち、このように解決および作成されます。

于 2014-02-13T05:13:33.103 に答える