我正在使用 grunt 连接我的 .js
我的 Angular 应用程序的文件。
我刚刚完成并整理了代码库以遵循讨论的约定 here ,具体来说,将我的代码分组为代表功能的小模块。
但是,我发现如果在声明模块之前使用了模块,则连接顺序似乎会破坏应用程序。
例如:
|-- src/
| |-- app/
| | |-- userProfile/
| | | | userProfile.js
| | | |-- deposits/
| | | | |-- depositFormCtrl.js
在哪里:
// userProfile.js
var userProfile = angular.module('userProfile',[])
// depositFormCtrl.js
angular.module('userProfile')
.controller('DepositFormCtrl', function($scope) {...});
当 grunt 执行连接时,
depositFormCtrl.js
出现在 userProfile.js
之前.这会导致应用程序抛出错误,提示:Uncaught Error: No module: userProfile
我看到很多关于使用 RequireJS/AMD 管理模块加载顺序的可能性的讨论。然而,经常有人说这是矫枉过正/不需要,as Angular handles this for you .
例如:Angular 团队的 Brian Ford mentioned :
My personal take is that RequireJS does too much; the only feature that AngularJS's DI system is really missing is the async loading.
他还说elsewhere他不推荐使用 Angular 的 RequireJS。
我还看到提到使用 angular-loader.js ,如 seed project 上所示.但是,据我了解,(官方文档很少)加载程序旨在解决加载模块乱序的问题,而不是在使用之前对其进行引用。
将 angular-loader.js 添加到我的项目中并没有解决问题。
是否有我应该使用的声明来防止我遇到的错误?
声明模块和 Controller 的正确方法是什么,以便连接订单文件不会影响运行时的代码?
最佳答案
我有时使用的一种技术是将声明放在连接文件的开头。我通过将它们放在一个专用文件中来做到这一点,该文件将是第一个由串联实用程序拾取的文件。
//app/_declarations.js
angular.module('userProfile',[]);
//app/userProfile/userProfile.js
angular.module('userProfile')
.config(['$routeProvider', function ($router) {...});
//app/userProfile/deposits/depositFormCtrl.js
angular.module('userProfile')
.controller('DepositFormCtrl', function($scope) {...});
可能并不适合所有场景,但易于设置和理解。
关于AngularJS : File concatenation breaks module declaration order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17082092/