13

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

0

2 Answers 2

38

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

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

Sign up to request clarification or add additional context in comments.

4 Comments

I'm using angular.module('myModuleName').controller('MyControllerName', ($scope) ->)
I guess I'll edit the post with that so people aren't encouraged to create global variables (those mess up tests bad)
I believe you need an empty array as a second parameter after the module name. angular.module('myApp', []).controller('MyController', ($scope) ->)
If you supply the empty array, it will create a new module called 'myApp' with no dependencies. If you have no array, it will just get the existing 'myApp' module.
0

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.

2 Comments

Doing that will put everything into the global scope, which is generally frowned upon (and specifically called out in the AngularJS docs but oddly not followed in their own tutorial or seed project's controllers -- but is for directives, filters, and services).
I agree this shouldn't be done, for the reason (unnecessarily pollutng the global scope) mentioned above by Todd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.