November 17, 2016

Creating Angular 1 components in ES2015 syntax

Recently I have been working on transitioning my company’s Angular 1x Single Page Application(SAP) to ES2015 to prepare us to update to Angular 2 in the feature. At work we are using Webpack as our bundler with the Babel 6 loader to transpile our code back to ES5.

Note that the following code assumes that you are using a bundler like Webpack with the appropriate loaders. I will not post my Webpack configuration since you can easily find that information on their site as well as Babel’s. The modules are written in a way that you can easily swap the bundler or transpiler with little modifications to your code.

 

Creating an Angular controller in ES2015 syntax

export default class SomeController {
    constructor(someDependency) {
        this.someDependency = someDependency;
        this.title = 'The component title';
    }
    someMethod() {
    }
}

SomeController.$inject = ['someDependency'];

Notice how dependencies are being inject through the constructor method and using $inject. I am exposing the dependency by reassigning it to a property with the same name to the this object. That will make accessible in any of the methods using the this keyword.

Creating a component in ES2015 syntax

import SomeController from './somecontroller.ctrl';

const SomeController {
    template: "<h1>{{vm.title}}</h1>",
    controller: SomeController,
    controllerAs: 'vm'
}

Creating an Angular module as a ES2015 Module

import SomeComponent from './some-component.component';

const SomeModule = angular
    .module('someModule', [])
    .component('someComponent', SomeComponent);

export default SomeModule;

 

The module becomes the single source where everything that belongs to it is declared using Angular’s interface.  It also includes any type of providers or services and will make it much easier to upgrade to Angular 2 because you are creating native classes and object literals when declaring each peace.

One caveat is that the new syntax favors services over factories. You may recall that one of the differences in how they are declared is that factories return an object where services are constructor functions.