2016-08-12 54 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