当我使用RequireJS和AngularJS时,出现了一些非常奇怪的问题。我通过RequireJS成功加载了所有的angular依赖项。当我在Chrome开发者工具中打开Sources面板时,我可以看到这些脚本已经下载了。但是Angular仍然在控制台中抛出一个错误,说它无法实例化该模块:
Uncaught Error: [$injector:modulerr] Failed to instantiate module MyTestApp due to:
Error: [$injector:nomod] Module 'MyTestApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure...<omitted>...0)
似乎当使用RequireJS加载Angular时,无法与HTML页面中的“ng-app”标签绑定。我不确定这是否是问题,但在手动将angular.min.js导入到HTML页面中时,一切都正常运行。
当我使用RequireJS和Angular时,我有什么做错了吗?我应该如何结合使用这两个技术?以下是我的代码示例: index.html
<!doctype html>
<html lang="en" ng-app="MyTestApp">
<head>
<meta charset="utf-8">
<title>AngularJS</title>
<link rel="stylesheet" href="css/style.css"/>
<script data-main="main" src="js/require.js"></script>
</head>
<body>
<div ng-controller="TestController">{{helloMessage}}</div>
</body>
</html>
main.js
require.config({
baseUrl: "scripts/app",
shim: {
"angular": {
exports: "angular"
},
"angular.route": {
deps: ["angular"]
},
"bootstrapper": {
deps: ["angular", "angular.route"]
},
},
paths: {
"angular": "../angular",
"angular.route": "../angular-route",
"bootstrapper": "bootstrapper"
}
});
require(["angular", "angular.route", "bootstrapper"],
(angular, ngRoute, bootstrapper) => {
bootstrapper.start();
}
);
bootstrapper.js
function run() {
app = angular.module("MyTestApp", ["ngRoute"]);
app.controller("TestController", TestController);
console.log(app); //Prints object to console correctly, ie, angular was loaded.
}