Creating Angular Controllers using TypeScript

Recently I decided to move one of my project to typescript, project was getting bigger was getting harder to maintain, and managing big projects becomes even more problematic if tooling is not great, I mean, there are lot of IDE's that does the great job but it's still not on par with the tooling we get for other languages such as PHP, .NET

So I decided to use TypeScript, which is nothing but a superset of JavaScript, in fact valid JavaScript is also valid TypeScript so I just changed all of my files extensions from .js to .ts and started to convert the project from one by one, and within a week, I successfully migrated from JavaScript to TypeScript. 

Angular 2 is knocking the door although you can write your Angular2 apps in ES5, ES6, but TypeScript is the preferred way  so it's a good time to get a hang of it.

I will discuss my typescript workflow in upcoming tutorials but for this tutorial I will talk about angular controllers using TypeScript.

What We are going to build

In this very simple example, we are going to create A Controller which will simply add or subtract value and save it in the cookie.

Let's start with writing Controller in JavaScript

MathController in JavaScript( mathcontroller.js)

angular.module('app').controller('MathController', ['$cookieStore', function($cookieStore) {

    var vm = this;
    vm.total = 0;

    vm.addToTotal = function () {
        vm.total = vm.total + 1;
        saveTotalToCookie(vm.total);
    }

    vm.subtractFromTotal = function() {
        vm.total = vm.total - 1;
        saveTotalToCookie(vm.total);
    }

    function saveTotalToCookie(total) {
        $cookieStore.put('total', total);
    }

}]);

As you can see we have two functions to add and to subtract from total which is initialized as 0, we are also injecting $cookieStore in this Controller,  now let's write the same functionality in TypeScript.

MathController in TypeScript( mathcontroller.ts )

interface IMathController {
        total : number;
        addToTotal() : void;
        subtractToTotal() : void;
        saveTotalToCookie(total : number) : void;
    }


    class MathController implements IMathController {

        static $inject = ['$cookieStore'];

        total:number;

        constructor( private $cookieStore : ng.cookies.ICookieStoreService) {
            this.total = 0;
        }

        addToTotal():void {
            this.total = this.total + 1;
            this.saveTotalToCookie(this.total);
        }

        subtractToTotal():void {
            this.total = this.total -1;
            this.saveTotalToCookie(this.total);
        }

        saveTotalToCookie(total : number ):void {
            this.$cookieStore.put('total', total);
        }

    }

    angular.module('devArt').controller('MathController', MathController);

Let's break it down into Pieces

As you can see we are starting with the interface which is part of the TypeScript and only used for development purpose, and will not be included in transpiled JS output. This interface will make sure that we implement all the method and properties in the Class which is implementing this interface( in this case MathController ).

interface IMathController {
        total : number;
        addToTotal() : void;
        subtractToTotal() : void;
        saveTotalToCookie(total : number) : void;
    }

Now we are going to create the MathController class and injecting "$cookieStore" service as a static property named $inject, also let's save it as class property in the constructor.

class MathController implements IMathController {

    static $inject = ['$cookieStore'];

    constructor( private $cookieStore : ng.cookies.ICookieStoreService) {}
 
}

We are implementing IMathController so we must create three-member methods and one member property to fulfil the contract, let's also initialize member property total with 0 in the constructor.

class MathController implements IMathController {

    static $inject = ['$cookieStore'];

    total:number;

    constructor( private $cookieStore : ng.cookies.ICookieStoreService) {
        this.total = 0;
    }

    addToTotal():void {
        this.total = this.total + 1;
        this.saveTotalToCookie(this.total);
    }

    subtractToTotal():void {
        this.total = this.total -1;
        this.saveTotalToCookie(this.total);
    }

    saveTotalToCookie(total : number ):void {
        this.$cookieStore.put('total', total);
    }
}

Finally, we need to Register the controller which is business as always.

angular.module('app').controller('MathController', MathController);

Note: Controller registration must come after the class not before, or else it will generate an error.

That's it, guys, it might seem a lot more trouble at first but later down the road it will make our project lot more manageable and easier to maintain and extend finally if you have any questions ask us below in the comment section or head over to our forum and create new thread.

Something to say? Tell us in comment section.