Last week I attended a hackathon, and to familiarize myself with ES6 in combination with Angular 1.x I decided to use just that. And it was a lot easier then I expected!

Lets say we have the following application structure

/app

/example (main component file)

example-controller (component controller)

example-directive (component directive)

example-service (component service)

We want to use ES6 classes wherever possible, and I will explain how to do it per file.

Controllers & Services

Controllers and Services are the easiest to write in ES6.

example-controller

example-service

Two things you might notice, first is the “export default”, this means we can simply write

import ExampleService from ‘./example-service/example-service.js’;

Instead of

import { ExampleService } from ‘./example-service/example-service.js’;

The other thing you might notice is the “ExampleService.$inject”, this tells angular what dependencies to inject into our Class. You could also use something like ngAnnotate if you prefer that

Directives

Directives are a bit more complicated to write in ES6 syntax because Angular expect an object literal, not a constructor function. This can however be easily fixed.

example-directive

As you can see we can still use best practices, such as the controllerAs and the bindToController syntax to prevent the use of scope. The directive’s controller is defined as another Class.

Define our component

Now that we defined all sub-components of our component file we can define them in a main file.

As you can see only the directive syntax is different because Angular expects an object literal, not a constructor function.

Use a module loader

We can use a bundler such as webpack to combine all code in a single bundle. The benefit of using webpack is that we can also compile our code to ES5 while bundling to support the current browsers.

You can find the complete code here