Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 566
dantheta Avatar asked Aug 13 '12 01:08

dantheta


People also ask

What is the use of CoffeeScript?

CoffeeScript is a programming language that compiles to JavaScript. It adds syntactic sugar inspired by Ruby, Python, and Haskell in an effort to enhance JavaScript's brevity and readability. Specific additional features include list comprehension and destructuring assignment.

How do I know if CoffeeScript is installed?

The coffee and cake commands will first look in the current folder to see if CoffeeScript is installed locally, and use that version if so. This allows different versions of CoffeeScript to be installed globally and locally.

How do I use CoffeeScript in HTML?

If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.


1 Answers

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

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

like image 176
Andrew Joslin Avatar answered Oct 21 '22 02:10

Andrew Joslin