2016-08-12 9 views
1

次のコードを見てください。角度コールランダムサービス!どうして?

主なアプリケーション:

(function(){ 
    var app = angular.module("myApp",["aSubApp","anotherSubApp"]); 
    var aController = function($scope, subService){ 
    subService.childService(); 
    } 

aController.$inject = ["$scope","subService"]; 
app.controller("testController",aController); 

app.service("parentService",function(){ 
    this.parentalService = function(){ alert("Parenting Services"); } 
    }); 
})(); 

、サブモジュール...

サブモジュール1:

(function() { 
    'use strict'; 
    var aSubApp = angular.module("aSubApp", []); 

    var subService = function (parentService, anotherService) { 
     this.childService = function() { 
      alert("Can I call random services???. I Don't know if they exist"); 
      parentService.parentalService(); 
      // This doesn't call the service defined beneath. 
      anotherService.aRandomService(); 
      alert("Looks like they do!."); 
     } 
    } 
    var anotherService = function() { 
     this.aRandomService = function() { 
      alert("another random SubService!!!"); 

     } 
    } 
    aSubApp.service("anotherService", anotherService); 
    subService.$inject = ["parentService", "anotherService"]; 
    aSubApp.service("subService", subService); 
})(); 

サブモジュール2:

(function() { 
    'use strict'; 
    var anotherSubApp = angular.module("anotherSubApp", []); 

    var anotherService = function() { 
     this.aRandomService = function() { 
      alert("A random SubService!!!"); 

     } 
    } 
    anotherSubApp.service("anotherService", anotherService); 
})(); 

subService.childServiceのコードはなぜ機能しますか? parentServiceとanotherServiceがどこにあるのか分からないと教えてくれませんか?彼らは依存モジュールではないので?それはJSのことですか?

答えて

1
var app = angular.module("myApp",["aSubApp","anotherSubApp"]); 

あなたのメインアプリでaSubAppanotherSubAppモジュールを注入しているので、dependentサービスもごmyAppにご利用いただけます。

あなたmyAppモジュールのごindex.htmlを見れば、あなたはそれを見てみることができます、すべてのJSファイルが存在し、私は今、質問を変更した

+0

"メインアプリケーションにaSubAppとanotherSubAppモジュールを注入しているので、従属サービスもmyAppで利用できます。" - これは私が受け入れるが、なぜ 'anotherSubApp'は 'aSubApp'で利用できるのか、これは私が想像することはできない! – anchreg

+0

@anchreg:aSubAppにこれがあるので、aSubApp.service( "anotherService"、anotherService);あなたはここに別のサービスを宣言しています... – Thalaivar

+0

しかし、私は私のモジュールaSubAppのanotherServiceを意味しました。私が得る警告はanotherSubAppのanotherServiceからのものです。これはaSubAppが知らない! – anchreg

0

基本的に、ページには1つのng-appしかありません。それをすべて1つの大きなオブジェクトと考えてください。依存関係を追加するだけでそのオブジェクトにプロパティが追加されます。したがって、メインオブジェクトには、アプリケーションで使用するすべてのサブモジュールプロパティが含まれている必要があります。アプリケーション全体に使用される主要オブジェクトは1つだけです。これらのサービス、ディレクティブ、コントローラなどはすべて、現在マスターアプリモジュールに統合されており、どこでも使用できます。

EX:

がアプリでそのようなngTableなどの任意のプラグインを追加するとしましょう。それは、アプリを通じてアクセス可能です。したがって、あなたのサブモジュールサービスについても同様です。

+0

[subService,parentService,anotherService]に含まれていることに気づくでしょうか? – anchreg

関連する問題