我目前正在与RequireJS一起构建AngularJS的基础,到目前为止我已经完成了所有工作。在这一点上,我还有一件事我不明白。我有一个创建角度模块的文件,当创建该模块时,它需要一个控制器并将其分配给模块。奇怪的是,控制器需要模块作为依赖,而在模块的文件中模块尚未返回,因为require语句在return语句之前执行。这种方式看起来似乎有效,但它有难闻的气味。
模块文件:
// Home is defined here and can later be used in controllers (and Services)
define('home', ['require', 'angular'], function(require, angular) {
var homeModule = angular.module('AngularBase.home', ['AngularBase.core']);
homeModule.config(['$controllerProvider', '$provide', '$compileProvider', function($controllerProvider, $provide, $compileProvider) {
// We need this in order to support lazy loading
homeModule.controller = $controllerProvider.register;
homeModule.factory = $provide.factory;
// And more, not relevant at this moment
}]);
// It loads the controller that depends on this module here
require(['modules/home/controllers/homeController'], function() {
// Dependencies loaded
});
// Yet in my mind controllers that need this module can only use it when the following return statement is called.
return homeModule;
});
控制器文件:
// As you can see this controller depends on home while home hasn't returned its module yet
// Yet it seems to work just fine
define(['home'], function(home) {
home.controller('homeController', ['$scope', 'homeService', function($scope, homeService) {
$scope.title = 'Home controller';
}]);
});
我认为这样做并不是一个好方法,因此我需要一些关于如何以干净的方式实现这一点的建议。我想通过控制器文件中的angular.module('AngularBase.home')
抓取AngularBase.home模块并在此定义我的控制器。然而,这不再允许我通过RequireJS的map函数插入mockModule以在此控制器中进行测试。
map: {
'*' : {
'home' : 'mock-module'
}
}
有关如何将其重构为更清洁的解决方案的任何建议吗?