Skip to content

Instantly share code, notes, and snippets.

@JeroMiya
Created July 12, 2013 03:05
Show Gist options
  • Save JeroMiya/5981105 to your computer and use it in GitHub Desktop.
Save JeroMiya/5981105 to your computer and use it in GitHub Desktop.
A template for defining an angular controller in TypeScript, which allows for minimization and does not require explicit field declarations for injected constructor arguments.
/// <reference path="Scripts/typings/underscore/underscore-typed.d.ts" />
/// <reference path="Scripts/typings/angularjs/angular.d.ts" />
module ts {
export class Base {
// you can have a static $inject here, but it will get ignored.
// only define it if you plan on using your base class as a
// controller directly
constructor(private $http: ng.IHttpService) { }
public getData() {
alert("getting data");
this.$http.get("api/some_data").then(
_ => alert("got " + _.data),
_ => alert("got error: " + JSON.stringify(_)));
}
}
// Works for subclasses too
export class Controller extends Base {
// use a static variable to declare injected arguments
// otherwise your code will break if minimized.
static $inject = ["$scope", "$http"];
constructor(private $scope: ng.IScope, $http: ng.IHttpService) {
super($http);
$scope["vm"] = this; // when using bracket syntax, $scope becomes an <any>
}
public title: string = "hello";
}
}
angular.module("app", []).controller("Controller", ts.Controller);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment