Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm working on a web app using AngularJS and Typescript and I'm trying to find the best way to take advantage of Typescript when it comes to defining controllers. Intuitively a controller would just be a TypeScript class but AngularJS wants you to put everything into the $scope variable.

In the lasted Alpha release of AngularJS (1.1.5) they have added a new 'controller as' syntax. I've heard that this new syntax should help integrate with languages like Coffeescript and TypeScript but I don't quite understand how. If anyone has a sample of using this new syntax with TypeScript or CoffeeScript or can provide some insight into how it could be done I'd greatly appreciate it.

Thanks!

share|improve this question

2 Answers

up vote 2 down vote accepted

Yes it works fine. Just create your class e.g MainController. Then in your view use ng-controller='MainController as vm'. All properties of MainController class become members of $scope.vm

share|improve this answer
 
So all I have to do is create a class who's name matches whatever is in ng-controller and angular will call it's constructor? Also if I put parameters like $location and $log in the constructor will they be injected? –  rob May 30 at 3:48
 
@rob yup. Just make sure the generated js is loaded. –  basarat May 30 at 4:02

This is what worked for me with CoffeeScript classes.

class MainCtrl
  newThing: ""
  constructor: (@model)->

  someThings: ->
    @model.awesomeThings

  addThing: ->
    @model.addThing(@newThing)


app.controller 'MainCtrl', ['ThingService', (model)-> 
    new MainCtrl(model)
]

You can see the full example on my plunk.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.