2014-10-28 49 views
0

如何在requirejs環境中返回多個角度模塊?Angular + Requirejs - 如何返回多個模塊?

這是我的app.js,

define([ 
    'angular', 
    'angular-route', 
    'jquery' 
], function (ng,ngRoute,$) { 
    'use strict'; 
    console.log($('h1').length); 

    return ng.module('myApp', ['ngRoute']); 

}); 

我需要一些更多的模塊返回,

ng.module('myAppModule1', ['ngRoute']); 
ng.module('myAppModule2', ['ngRoute']); 
ng.module('myAppModule3', ['ngRoute']); 

控制器例子,比如我想在app.js獲得 'myAppModule3' ,

define(['app'], function (app) { 
    var myAppModule = angular.module('myAppModule3'); 
    myAppModule.controller('welcomeController', ['$scope', function($scope) { 
     //your minsafe controller 
     $scope.message = "Message from WelcomeController"; 
    }]); 
}); 
+1

我看到你已經編輯你的問題回到它是什麼。這是正確的做法。否則,你會有[變色龍問題](http://meta.stackexchange.com/questions/43478/exit-strategies-for-chameleon-questions)。你所問的新問題是一個*不同的問題,需要一個*不同的問題。簡而言之,你創建你的模塊兩次:一次使用'ng-app'指令,一次使用'ng.module'調用。 – Louis 2014-10-28 17:58:50

+0

感謝路易斯的回覆! :D – laukok 2014-10-29 04:11:40

回答

1

您可以將app.js更改爲返回一個對象LDS是模塊:

define([ 
    'angular', 
    'angular-route', 
    'jquery' 
], function (ng,ngRoute,$) { 
    'use strict'; 
    console.log($('h1').length); 

    return { 
     myApp: ng.module('myApp', ['ngRoute']), 
     myAppModule1: ng.module('myAppModule1', ['ngRoute']), 
     myAppModule2: ng.module('myAppModule2', ['ngRoute']), 
     myAppModule3: ng.module('myAppModule3', ['ngRoute']) 
    }; 
}); 

,改變你的控制器是這樣的:

define(['app'], function (app) { 
    app.myAppModule3.controller('welcomeController', ['$scope', function($scope) { 
     //your minsafe controller 
     $scope.message = "Message from WelcomeController"; 
    }]); 
}); 
+0

謝謝。但它不起作用。我得到一個錯誤 - 'TypeError:app.controller不是函數 \t app.controller('HomeCtrl',['$ scope',function($ scope){'... – laukok 2014-10-28 16:27:37

+1

你必須調用'app .myAppModule.controller',而不是'app.controller' – Louis 2014-10-28 16:28:37

+0

'myAppModule'從哪裏來的? – laukok 2014-10-28 16:41:11

1

通用(非角專用)的方法是使用一個對象:

return {module1: /*..*/, module2: /*...*/ }; 

然後你只需訪問以下值:

define(['app'], function (app) { 
    var module1 = app.module1; 
}); 

然而,在Angular中,您只是在Angular全局中註冊了'myAppModule1'。有沒有必要做對象回報,你可以使用角度對象檢索註冊模塊:

define(['angular'], function (angular) { 

    var module1 = angular.module('myAppModule1'); 
    // without extra parameter it tells angular to retrive an existing 
    // module 
}); 

更新:我只是意識到,你在你的代碼做了。它沒有奏效?也許是你有一個依賴性問題,確保首先加載app.js

+0

謝謝。但我得到這個錯誤'TypeError:app.controller是不是一個函數 \t app.controller('HomeCtrl',['$ scope',function($ scope){'.... – laukok 2014-10-28 16:26:45