TypeScript: Angular 1.5 Quickstart

We recently started a new project and decided to use TypeScript along with Angular 1.5. Angular 1.5 introduces a new abstraction called a “component” which closely resembles Angular 2’s component based approach. Surprisingly, there isn’t a lot of simple TypeScript sample code available for Angular 1.5 so I decided to throw something together in case anyone else is looking. The code is available at https://github.com/Setfive/ng_typescript_starter and a live demo of it is running at http://code.setfive.com/ng_typescript_starter.

So what are some standouts with TypeScript and Angular 1.5?

  • The 1 way bindings components introduce are easier to reason about but having to explicitly add functions for “outputs” does add some verbosity
  • Related to that, there’s a fair amount of boilerplate to create a single component since you have to define 2 classes
  • Dropping $scope in favor of automatically binding the controller object to $ctrl in templates is great – especially with TypeScript classes
  • Related to that, without $scope for events it’s unclear when it’s appropriate to use $rootScope for an event bus
  • You can write typesafe code for almost all of your controller business logic
  • It’s really unfortunate the TypeScript compiler can’t typecheck your Angular templates
  • Using the $inject annotation with component classes looks “right” versus the “array like” syntax
  • You need to be somewhat cognizant of matching your @types annotations with the correct version of the library you’re using
  • Using components with ui-router makes it fairly difficult to communicate between sibling views

Anyway, beyond fighting with build tools to convert a TypeScript project into usable JavaScript the language part has been great to work with. We ended up using Browserify with tsify but it was pretty frustrating to get it working. I might of missed something but it seems like I needed tsify available in a separate node_modules directory from the project source. The demo app is setup this way for that reason.

As always, questions and comments are welcome!

Javascript, Angular, or how I learned to love the bomb

Enter the dragon

Interning with Setfive for the last couple of months has given me the opportunity to both work with numerous, modern-day technologies and transition into being a more confident, organized developer. One technology in particular that I’ve had the chance to learn about and use extensively during my internship here is the JavaScript programming language. Programming with an MVC framework like AngularJs has shown me the many facets of the JavaScript language and given me an interesting foray into learning JavaScript from the top down.

Coming from a mainly C++ background the first thing I noticed about JavaScript was its flexibility. The mixture of the dynamic typing, along with the support of multiple programing paradigms (Functional programming and Imperative programming) gave me a freedom to program any way that I saw fit and do things that I never even thought were possible in a language with a stricter typing system. However this freedom definitely comes with a price, sometimes making even moderately complex programs both hard to navigate, and even harder to debug.

This lack of an inherent language structure, though initially causing a few headaches and even more than a few fist shaking bugs has, over time, helped ingrain both strong development skills as well an inherent need to intuitively structure code. Both of these skills are at the forefront of programming with AngualrJs.

Leveling up

My experience with Angularjs has definitely been an incredibly positive one, although the beginning was quite rough. Actually, the beginning was fairly easy however, the step after the “hello (insert name bound from text box)” step was actually the rough one. With Angular, easy things are very easy but can become difficult very quickly as soon as you are trying to develop something that is not so rudimentary.

My first experience with Angular came in the form of writing unit tests for a project that was under development here during the Summer. I spent a couple of weeks delving through a large Angular application written by one of our head engineers. After my introduction to the framework I was given the chance to use it for some development while working on some frontend modules for the Rotorobot site. These are the main challenges that I ran into while trying to learn Angular Js.

The Tough Stuff

The first challenge that I had to overcome was understanding the structure of the Angular framework. Being very inexperienced with the design pattern of Model View Controller (MVC) made this aspect the hardest part of learning Angular. Angular implements MVC by having the developer split their application into MVC components and then acts as a pipeline connecting them together. It is a robust MVC framework that promotes complicated integration of different components into whole applications. If you don’t have a sense of how the pieces fit together then the “Set it and forget it” or 2-way data-binding nature of the framework can easily turn into one of your biggest headaches.

The second challenge with learning Angular was understanding the way that scoping works within the context of the framework. What possibly could have possessed the developers of Angular to name one of the most confusing parts of their framework the same name as one of JavaScript’s most confusing aspects –who knows. In order to use some of the most powerful features of Angular such as, custom directives, it was really important to understand how scoping works or else it’s virtually impossible to link programs together. Developers would be left with a pile of stateless, independent components responsible for various tasks of the application rather than a connected working whole.

The last major challenge with learning Angular was thinking in terms of modularity. With things like custom directives, and the various service providers being at its core, the Angular framework really helps to promote code modularity. And breaking your application into small, reusable, testable components. This concept is huge in Angular, and I felt like seeing it work within the context of the framework has made me a better JavaScript programmer overall.

Overall I thoroughly enjoyed my time with Angularjs and felt like I learned a significant amount about structuring web-based applications. I am glad to have been given some experience with a modern JavaScript MVC framework and I wouldn’t hesitate to use Angular again in the future.

AngularJS: Using dynamic content with $compile

One of the more opaque concepts about AngularJS is the process that converts a chunk of HTML from a template into “Angularized” HTML which is then inserted into the DOM. During this conversions, custom directives are replaced with their corresponding HTML content, Angular directives like ng-repeat are processed, and any event handlers of interest are wired up. As it turns out, Angular’s $compile service is what’s responsible for making the magic happen. OK great, but why is this interesting or important? Because leveraging the $compile service directly lets you take dynamic content and process it to enable Angular directives and behaviors.

Since examples are always helpful, here’s an admittedly contrived one that we’ll walkthrough. Imagine that we’re building a WordPress slideshow plugin and we want to support custom themes for individual slides. So in our plugin, a user would be able to modify the HTML that displays a slide, we’d save it to the database, and then retrieve that template when we render the slides. For arguments sake, let’s assume the “default” template for the slideshow looks something like this:

As you can see, we’ve got a few directives and by default we’re displaying some description. Generally, we could set this up by creating a “slide” directive that looks something like:

Great, nothing to crazy but with this setup there’s no way to supply dynamic HTML from our database to use in the template. In order to allow a custom template you’d just need to modify the directive to look something like:

And then you’d be able to use it with:

The key difference is that in the modified directive the template is inserted into the directive’s element using “angular.element(el).html(scope[“slide”].template);” and then finally the $compile service is invoked to process the regular HTML to get Angular magic.

Anyway, as always questions or comments welcome!

AngularJS: onLoad from an iframe directive

A couple of days ago in my journey down the AngularJS rabbit hole I ran into an interesting issue. If you have a directive that’s dynamically adding an iframe tag how can you set an onLoad handler on the iframe with access to the directive’s $scope?

Interestingly, the top StackOverflow answer on Google recommends adding a function to the window object and then setting the onLoad attribute to that function. Although it works, this approach is decidedly not “the Angular way” and would definitely become unwieldy with more than one iframe on the page. I poked around a bit and turns out there’s a better way to do this. The “trick” is that it’s possible to access a directive’s $scope from inside its link function so you can set onLoad on the iframe element from there. This post provides an overview but it’s a bit light on details so here’s a concrete example.

Javascript: Mixins in AngularJS

We’ve been doing a bit of AngularJS work (more on that later) recently and true to its reputation there’s an “Angular way” to accomplish most things. Interestingly, one area where I couldn’t find a “one true way” was how to facilitate mixins between controllers or scopes.

Quickly taking a step back, a “mixin” is a form of horizontal reuse that allows two objects to share code without necessarily sharing a common ancestor in an inheritance chain. With concrete examples, you might have a Dashboard and Billing controller which need to share formatting logic but nothing else you’d want to use mixins vs. traditional inheritance. In traditional object oriented language mixins are typically referred to as Traits.

Anyway, back to AngularJS. Let’s say we have some simple logic that we want to share between two scopes:

It’s a contrived example but the “idea” is that you want to share the “selectAnswer” and “getAnswerClass” functions between $scopes of two unrelated controllers. After doing some research, it seems like the cleanest way to do this in Angular is to create a service that contains the functions, inject that into the controller, and then use angular.extend() to add them to the $scope as needed:

And that’s pretty much all there is to it. I’m pretty new to the Angular dance so I’d love any feedback!