dantheta
dantheta

Reputation: 1107

Angularjs breaks with coffeescript function expression

I'm working on integrating AngularJs into an example Nodejs application. My controller is as follows:

UsersCtrl = ($scope, $http) ->    
   $scope.newUser = {}
   $scope.users = [
     name: "aloman"
     email: "[email protected]"
   ]

which compiles into javascript:

// Generated by CoffeeScript 1.3.3
(function() {
  var UsersCtrl;

  UsersCtrl = function($scope, $http) {
    $scope.newUser = {}; 
    return $scope.users = [ 
      {   
        name: "aloman",
        email: "[email protected]"
      }   
    ];  
  };
}).call(this);

The code above breaks with console log:
Error: Argument 'UsersCtrl' is not a function, got undefined

However removing the anonymous function wrapped around the compiled javascript works fine. The working code is shown below.

var UsersCtrl;
Usersctrl = function($scope, $http) {
    $scope.newUser = {};
    $scope.users = [{
        name: "aloman",
        email: "[email protected]" 
    }];
}; 

Any reason why my compiled code isn't working. I have a feeling it has to do with Angular's scope injection. I'm using AngularJS 1.0.1

Upvotes: 13

Views: 5096

Answers (2)

Andrew Joslin
Andrew Joslin

Reputation: 43023

It would be best to use this syntax so you don't pollute the global scope:

angular.module('myApp').controller('MyController', ($scope) ->)

Upvotes: 38

TheHippo
TheHippo

Reputation: 63139

Despite that all current answers are right there is a 3rd option:

When you compile you CoffeeScript to JavaScript make sure you set the --bare option to the CoffeeScript compiler, which make him omit the function wrapper in the output.

Upvotes: 0

Related Questions