Creating AngularJS controller classes with TypeScript

I recently learned of AngularJS's "controller as" syntax. It allows you to define an indentifier for the controller instance that is controlling your view. This means you can then access properties of that controller.

<div ng-controller="ExampleController as example">
    <input type="text" ng-model="example.message" />
</div>

This syntax is an alternative to the controller defining data directly on the scope. It is particularly useful when working with TypeScript or CoffeeScript, which have a nice class syntax. We can define a controller as a class, with properties for the data to display and methods that handle UI events.

Here's an example AngularJS application, written in TypeScript:

And here's the HTML for that application:

Would you like access to the sample code repository?

Subscribe to my web development mailing list.

No spam, just occasional web development tips, posts and sample code. Unsubscribe at any time.

Comments
blog comments powered by Disqus