Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does coffeescript angular demo fail in jsfiddle when an identical javascript one works?

I was building a jsfiddle angular app in coffeescript. It failed, and I reduced the failure to this minimal one:

<body ng-app="MyApp">
    <div ng-controller="MyController">
        {{text}}
    </div>
</body>

This javascript fiddle works: http://jsfiddle.net/nje7H/

var app = angular.module("MyApp", []);

app.controller("MyController", function($scope) {
    $scope.text = "Hello."
});

However, this coffeescript fiddle fails: http://jsfiddle.net/nje7H/1/

app = angular.module "MyApp", []

app.controller "MyController", ($scope) ->
    $scope.text = "Hello."

The console shows "Uncaught Error: No module: MyApp"

Why?

like image 262
user3727235 Avatar asked Dec 15 '25 13:12

user3727235


1 Answers

jsfiddle uses <script type="text/coffeescript"> elements and a library to compile the coffeescript on the client, which doesn't occur until the dom is ready and the code doesn't execute until after angular bootstraps. It will work if you manually bootstrap angular in your code (fiddle):

angular.bootstrap document.body, ['MyApp']

In a production environment you should be compiling your coffeescript into javascript for the browser and there wouldn't be a problem. See this question.

like image 172
Jason Goemaat Avatar answered Dec 17 '25 05:12

Jason Goemaat