AngularJS 遇到一个奇怪的问题求助

1272729223 · 2015年08月13日 · 最后由 1272729223 回复于 2015年08月14日 · 8099 次阅读

https://github.com/dfd07d/angular-amd-seed

master 分支,和 compare 分支。两份代码完全一样 (除了注释吧),我校对了好几遍。

但是在 master 分支下跑就报错,

Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:modulerr] Failed to instantiate module core due to:
Error: [$injector:nomod] Module 'core' 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.

在 comapre分支下就 ok。我擦!

谁能帮我看看么?

我觉得主要的问题应该是出在这几个文件中,但自己已经看不出来了。

js/
|-- app.js
|-- main.js
|-- core/core.js

main.js

;(function() {

require.config({

    // 设置`alias`
    paths: {
        "angular": '/bower_components/angular/angular',
        "angular.route": "/bower_components/angular-route/angular-route",
        "angular.resource": "/bower_components/angular-resource/angular-resource",
        "angular.cookies": "/bower_components/angular-cookies/angular-cookies",
        "ui.bootstrap": "/bower_components/angular-ui-bootstrap-bower/ui-bootstrap"
    },

    shim: {

        // 由于angular并非`define()`定义的模块
        // 所以手动导出为AMD支持的格式
        "angular": {
            exports: "angular"
        }
    },

    // 引入启动应用的模块`./bootstrap`
    deps: ["./bootstrap"]
})

}())

bootstrap.js

// 这里并非定义AMD模块
// 仅仅使用`require()`方法作为模块加载器
require([
    "angular",
    "./app"
], function( angular ) {

angular.element()
    .ready(function() {

        // 等待DOM READY之后,手动启动应用
        angular.bootstrap( document, [ "app" ] )
    })

})

app.js

define([
    "angular",
    "./core/core",
    "./ui/ui",
    "./prj/prj"
], function( angular /*core, ui, prj*/ ) { // 虽然我们这里得到了`core`,`ui`,`prj`模块的对象,
                                           // 但angular在定义module依赖的时候并不需要直接的对象
var app = angular.module("app", [

    // 这时候,module`core`,`ui`,`project`已经可以使用
    "core",
    "ui",
    "project"
])

// 配置`./app`模块
app.config(function( $routeProvider ) {
    $routeProvider.otherwise({
        redirectTo: '/projects'
    })
})

// 导出`./app`模块
return app

})

core/core.js

define([
    "require",
    "angular"
], function( require, angular ) {

var core

// 因为`angular.route`等并非标准AMD模块,
// 所以仅仅使用`require()`预加载进来,
// 然后导出返回值作为导出的`./core`模块
return require([
    "angular.route",
    "angular.resource",
    "angular.cookies"
], function() {

    // 创建module`core`
    core = angular.module("core", [
        "ngRoute",
        "ngResource",
        "ngCookies"
    ])

    // 返回给`require()`方法作为结果
    return core
})

})

跪谢!

#1 楼 @luikore 我也试过了,还是那个错误。

我本地运行你两个分支都是随机出现这个错误。。。应该是你的 angular 调用错误。。。具体的我也还在研究,暂时没啥头绪

研究出来了,修改在此 不是很懂 angularjs 和 requirejs,但是觉得define后,你应该不需要再写require

#4 楼 @flemon 谢谢,是这样,因为define()内部require()也是异步的,我以为 requirejs 的工作原理是不管如何,只要使用这两个方法,都是必须等待他们 deps 执行完之后才会执行 callback 的。其实不然。

#4 楼 @flemon 但是你现在的 PR 还是有点儿问题。晚点儿,我在 github 上回你好了。谢谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号