【问题标题】:AngularJS with CoffeescriptAngularJS 与 Coffeescript
【发布时间】:2017-05-30 12:18:32
【问题描述】:

我已经在 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.coffee

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!"
]

【问题讨论】:

  • 好吧,我用另一种方式做到了。安装了yeoman(因为之前我不知道这件事)并委托他为我做所有事情:)但仍然感谢您的回答。您可以将其添加到您的答案中,所以我会接受它作为完整答案:)

标签: javascript angularjs coffeescript


【解决方案1】:

浏览器本身不支持Coffeescript:您必须将其编译成Javascript。

您可以通过使用诸如 Grunt 或 Gulp 之类的任务运行器和适当的插件(gulp-coffeegrunt-contrib-coffee)或使用 Browserify 和适当的转换(coffeeify)“轻松”地做到这一点。 Yeoman 使用 Grunt/Gulp。

现在,关于错误:

<script src="coffee/app.coffee" type="text/coffeescript" ></script>

这个 sn-p 将有效地加载脚本但不会解释它。您可以获取它的内容并将其作为字符串进行操作(这是某些模板库所使用的),仅此而已。浏览器不会告诉你“嘿,我看不懂,这是咖啡脚本”。

页面加载完成后,由于是纯 javascript 而成功加载的 Angular 将解析您的 DOM,读取 ng-app="app",并尝试查看他是否知道模块 app。 不幸的是,您的脚本没有被解释,因此没有声明 app 模块:这就是您得到的错误!

【讨论】:

    猜你喜欢
    • 2017-09-30
    • 2013-07-10
    • 2014-02-27
    • 1970-01-01
    • 2013-08-13
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多