2016-08-12 28 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); 
})(); 

子單詞數:

(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文件都包含有[subService,parentService,anotherService]

+0

「您正在向主應用程序注入aSubApp和anotherSubApp模塊,因此依賴服務也可用於myApp。」 - 我接受,但爲什麼'anotherSubApp'在'aSubApp'中可用,這我不能幻想! – anchreg

+0

@anchreg:因爲您在aSubApp,aSubApp.service(「anotherService」,anotherService);你在這裏聲明另一個服務... – Thalaivar

+0

但是,我的意思是我的模塊aSubApp中的另一個服務。我得到的警報來自anotherSubApp的另一個服務,它是aSubApp不知道的! – anchreg

0

基本上你在頁面中只有一個ng-app。把它看作一個大對象。添加依賴關係只是爲該對象添加屬性。所以主對象需要包含應用程序使用它們的所有子模塊屬性。並且整個應用程序只有一個主要對象。所有這些服務,指令,控制器等現在都被組合到主應用程序模塊中,您可以在任何地方使用它們。

EX:

比方說,你在你的應用程序中添加任何插件,例如ngTable。它可以通過應用程序訪問。因此,您的子模塊服務也是如此。

+0

我現在已經修改了問題,你可以看看嗎? – anchreg