我已经用 AngularJS 做了一个测试应用程序,现在我尝试用咖啡来做一些不同的事情。问题是,它给了我这样的错误:
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' 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.
我不明白,为什么它看不到我的应用程序模块。这是我的代码:
<小时/>index.html
<!doctype html>
<html lang="en" ng-app="app">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="css/app.css">
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-animate/angular-animate.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/angular-resource/angular-resource.js"></script>
<script src="coffee/app.coffee" type="text/coffeescript" ></script>
<script src="coffee/controllers.coffee" type="text/coffeescript"></script>
</head>
<body>
<div class="view-container">
<div ng-view></div>
</div>
</body>
</html>
应用程序咖啡
app = angular.module 'app', [
'ngRoute'
'commentController'
]
app.config [ '$routeProvider',
($routeProvider) ->
$routeProvider.
when('/title', {
templateUrl: 'templates/title.html'
controller: 'CommentListCtrl'
}).
otherwise({
redirectTo: '/title'
})
]
和controllers.coffee:
commentController = angular.module 'commentController', []
commentController.controller 'CommentListCtrl', [ '$scope',
($scope) ->
$scope.hello = "HELLO!"
]
最佳答案
浏览器本身不支持 Coffeescript:您必须将其编译为 Javascript。
您可以通过使用任务运行程序(例如 Grunt 或 Gulp 和适当的插件( gulp-coffee 、 grunt-contrib-coffee ),或者使用 Browserify 和适当的转换( coffeeify )来“轻松”完成此操作。 Yeoman 使用 Grunt/Gulp。
现在,关于错误:
<script src="coffee/app.coffee" type="text/coffeescript" ></script>
此代码片段将有效加载脚本,但不会解释它。您可以获取其内容并将其作为字符串进行操作(某些模板库使用的是字符串),但仅此而已。浏览器不会告诉你“嘿,我看不懂这个,这是coffeescript”。
页面加载后,Angular(由于它是纯 JavaScript,已成功加载)将解析您的 DOM,读取 ng-app="app"
,并尝试查看他是否知道模块应用程序
。
不幸的是,您的脚本没有被解释,因此 app
模块没有声明:这就是您得到的错误!
关于javascript - AngularJS 与 Coffeescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27102889/