1

I'm using Coffeescript and am trying to define a controller which will use the "HomeController as homeCtrl" syntax.

angular.module('myApp.controllers',[]).controller("HomeController", ->

    @someArray = []

    # return
)

This is broken - the scope.homeCtrl is set as [] rather than the object {someArray: []}. I realize this is because Coffeescript automatically returns the last line of a function, so the transpiled return this.someArray = [] returns [] for the function. I can fix this by uncommenting the bare return command, or even something like return true or @baz='foobar'. But the really weird part is that this only messes up when the last line of the function returns an array. What's going on?

Steven Clontz
  • 945
  • 1
  • 11
  • 20

2 Answers2

1

That problem was killing me! It's actually not only just arrays. Just make it a habit to return at the end of your controllers.

EDIT: to be more specific. It's angular calls the function as a Constructor using the new keyword. Constructor behaviour is specified as specified in This SO Post

Community
  • 1
  • 1
mrBorna
  • 1,757
  • 16
  • 16
  • Yeah that's the solution for sure. I was interested in why it does that, however. – Steven Clontz Mar 26 '15 at 18:13
  • 1
    @StevenClontz It's because angular uses the 'new' keyword on the function. Since it's a constructor, the return value is the instance, so returning anything else makes javascript think thats your instance. Omitting a return value returns 'this' which would be the controller itself. Since coffeescript is auto-returning, we're left with that behaviour :) – mrBorna Mar 26 '15 at 19:11
  • Awesome, that's exactly what I was looking for. – Steven Clontz Mar 27 '15 at 15:11
0

You could use CoffeeScript class keyword to force CS to create a class constructor:

angular.module('myApp.controllers',[]).controller "HomeController", class
  constructor: ->
    @someArray = []

Or, you could create named class and then pass it to angular.js:

class HomeController
  constructor: ->
    @someArray = []

angular.module('myApp.controllers',[]).controller "HomeController", HomeController
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122