如何解决内置AngularJS应用程序的依赖性问题?

时间:2014-02-20 17:58:29

标签: javascript angularjs build gruntjs dependency-management

我是AngularJS的新手,正在创建一个使用Grunt构建的应用程序。

当我构建并运行我的应用程序时,我注意到与依赖性加载顺序相关的一些问题:

Uncaught Error: [$injector:nomod] Module 'mycompany.admin.forms' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.13/$injector/nomod?p0=mycompany.admin.forms 

在构建的app文件中,模块在声明之前正在使用:

angular.module('mycompany.admin.forms').controller('editController', ['$scope', function($scope) {
    // ...
}]);

angular.module('mycompany.admin.forms', [])

  .config(['$routeProvider', function($routeProvider) {
    // ...
  }]);

以下是我项目的gruntfile.js的相关摘要:

grunt.initConfig({
    distdir: 'build',
    pkg: grunt.file.readJSON('package.json'),
    src: {
        js: ['src/**/*.js'],
    },
    concat: {
        dist: {
            src: ['<%= src.js %>', '<%= src.jsTpl %>'],
            dest: '<%= distdir %>/admin/app.js'
        }
    }
    ...
});

我知道我可以通过将给定模块的所有源放入一个文件来解决这个问题;但是,我想尝试将每个事物(每个控制器,每个服务等)保存在自己的文件中。

如何解决此依赖项加载顺序问题?

2 个答案:

答案 0 :(得分:5)

grunt连接文件的顺序是什么?看起来你只是在读一个目录,如果模块声明所在的javascript文件位于控制器所在的文件之后,那么连接文件将以错误的顺序构建。

可能最简单的解决方案是明确列出包含模块声明的文件(带[])作为源数组中的第一个文件。

答案 1 :(得分:-1)

为了解决依赖性负载问题,我建议您使用Require.js

它与Angular配合得很好,你也有grunt plugin来进行构建。