2017-07-12 52 views
1

我正在製作在udemy上嘗試AngularJS:初學者指南,我遇到了一個奇怪的問題。以下代碼適用於課程經理,但不適用於某些用戶。複製代碼時未找到AngularJS控制器

的index.html

<html lang="en" ng-app='try'> 
    <head> 
     <script src="./js/angular.min.js"></script> 

     <script src="./js/app/app.module.js"></script> 
     <script src="./js/app/app.config.js"></script> 

     <script src="./js/app/blog-list/blog-list.module.js"></script> 
     <script src="./js/app/blog-list/blog-list.component.js"></script> 
    </head> 

    <body> 
     <div class='' ng-controller='BlogListController'></div> 
    </body> 
</html> 

app.module.js

'use strict'; 
angular.module('try', ['blogList']); 

app.config.js

'use strict'; 
angular.module('try', []) 
    .config(function(){}); 

博客-list.module.js

'use strict'; 
angular.module('blogList', []); 

博客,list.component.js

'use strict'; 
angular.module('blogList'). 
    controller('BlogListController', function(){ 
     console.log("hello") 
    }); 

我得到一個錯誤

名爲 'BlogListController' 控制器未註冊。

但是,如果在文件博客-list.component.js我更改模塊名稱:

'use strict'; 
angular.module('try').   <---- CHANGED THIS 
    controller('BlogListController', function(){ 
     console.log("hello") 
    }); 

它的工作原理。

爲什麼修復前的代碼對課程管理員有用?哪一個纔是真正的正確答案?

PS:所有內容都按照index.html文件指定的順序加載。

在此先感謝。

+0

因爲控制器不存在'try'模塊內部。你已經在html'ng-app ='try''中聲明瞭它。在html中添加'ng-pp =「blogList」'然後將工作 –

+0

@SibiRaj那麼爲什麼教師的代碼使用'ng-app =「try」'? –

+0

我不知道教練說什麼。一個簡單的邏輯。你已經在另一個模塊中定義了它。你怎麼能期望在某個地方工作,哪裏的控制器從未被定義 –

回答

1

try模塊加載時不依賴於blogList模塊,因爲app.config.js包含一個非常細微的錯誤。

請注意,angular.module函數可用於兩種方式:檢索模塊和創建新模塊。提供第二個參數時會創建一個新模塊。第二個參數包含模塊的依賴關係。

這意味着該模塊在此應用程序中的加載如下:首先,angular.module('try', ['blogList'])創建一個名爲try的新模塊,並依賴於blogList。然後angular.module('try', []).config(function(){})創建一個名爲try的新模塊,而不存在任何依賴關係,覆蓋以前的try

只需刪除第二個參數,以便app.config.js看起來是這樣的:

'use strict'; 
angular.module('try') 
    .config(function(){}); 

,它應該總是工作。