Tuesday, December 27, 2016

TypeScripting AngularJS 1.x - Directives

This post is part of TypeScripting AngularJS 1.x series.Other posts are listed below.

  1. TypeScripting AngularJS 1.x - Define module
  2. TypeScripting AngularJS 1.x - Define module - improvements for big enterprise apps Improvement
  3. TypeScripting AngularJS 1.x - Using $http 
  4. TypeScripting AngularJS 1.x - Directives

Angular Directives using TypeScript

Below is a mechanism to create typed Angular directives using TypeScript.

The main thing is that our directive class needs to implement ng.IDirective. After that we can have the corresponding ng.IDirective members. The advantage here is that we don't need to memorize or google for what are the members required for directive. Its all there in ng.IDirective

export class ProjectsDirective implements ng.IDirective {
    public restrict: string;
    public templateUrl: string;
    public controller: any;
    public controllerAs: string;
    public bindToController: boolean | { [boundProperty: string]: string };
    public scope: boolean | { [boundProperty: string]: string };
    constructor() {
        this.restrict = 'E';
        this.templateUrl = 'JS/app/projects.component.html';
        this.controller = "ProjectsController";
        this.controllerAs = "ctrl";
        this.bindToController = true;

Above code snippet is taken directly from my personal web site. The members such as bindToController, controller etc... are optional. This is not enough to get the ProjectsDirective available in our application. For that we have to register it with Angular application.

Code snippet below shows the registration.

AppModule.getInstance().registerDirective("projects", () => {
    return new ProjectsDirective() 

It gets the instance of the Angular module and calls the registerDirective function. The object here is  a wrapper over real Angular module object. That function in turn calls the real Angular.directive function.

Dependency injection

The dependencies to the directive can be accepted by the directive factory / creation function. That function then can pass those injected objects to the directive constructor. 

Sample code

The code is from my personal web site and it is in GitHub.
Simply clone the repo and compile using Visual Studio 2015. It uses TypeScript 1.8.

No comments: