Writing a Directive for AngularJS 1.3 using TypeScript.

I wanted to get a handle on using TypeScript as soon as possible with my current Angular 1.3 projects. My journey thus far.

Alabama Swirlsby Kirk Lougheed

So what did I do? I wrote one of my directives using TypeScript, and you know what… It wasn’t bad at all!

Here’s how I did it.

The Process

I first wrote the test for my directive, then ran them with file watching to ensure that I could have these going in the background as I made the different changes in my code. This I think is crucial.

The directive spec file.

The next step involved writing a basic, non-trivial AngularJS 1.3 directive. The code looked like this:

The directive in a written in a TypeScript file.

The directive was written in a TypeScript file. It runs wonderfully as can be expected, as TypeScript is a superset of Javascript.

After extracting the return function of the activityItem method to variables and adding the TypeScript styled type checking I ended up with two different files.

The Result

The first file (_app.core.ts) is a helper util that builds the directive:

Directive factory util.

The other file (activityItemDirective.ts) is the actual directive written in TypeScript:

Refactored ActivityItem directive written in TypeScript.

Closing notes and thoughts:

  1. I’m using the AngularJS TypeScript declaration file found here.
  2. Aaron Holmes’ blog post got me thinking.
  3. This could be made better if the Controller and Link were moved into the IsolateScope — perhaps?

Happy coding.

-harold campbell