Using ES6 with Angular 1.x
Alin Chiuaru
Junior Front-end Developer @ [e-spres-oh]
Why would you do that ?
- ES6 Specifications are final
- Angular 1.x is going to stay for a while
- Some features speed up development time
- Stay updated
Transpilers

Directives
//app/components/item/item.directive.js
import template from './item.html';
import controller from './item.controller';
import './item.css';
let itemDirective = function() {
return {
restrict: 'EA',
scope: {},
template, //no need to use key : val pair if both have the same name
controller,
controllerAs: 'vm',
bindToController: true
};
};
export default itemDirective;Directives (2)
//app/components/item/item.directive.js
import template from './item.html';
import controller from './item.controller';
import './item.css';
class ItemDirective {
constructor() {
this.restrict = 'EA';
this.scope = {};
this.template = template;
this.controller = controller;
this.controllerAs = 'vm';
this.bindToController = true;
}
// the module.directive() method expects a factory function
static directiveFactory() {
ItemDirective.instance = new ItemDirective();
return ItemDirective.instance;
}
}
export default ItemDirective;Controllers
//app/components/item/item.controller.js
class ItemController {
// Dependency Injection goes in here
// Use ng-annotate or ItemController.$inject = [$stateParams, ItemService];
/*@ngInject*/
constructor($stateParams, ItemService) {
//Add the dependencies to the context
this.$stateParams = $stateParams;
this.ItemSerivce = ItemService;
}
getItem() {
// 'this' in here is the 'this' out there
let id = this.$stateParams.id;
this.ItemService.getItem(id).then((data) => this.item = data );
}
}
export default ItemController;Services
MUST be defined using the module.service(fn)
class ItemService {
/*@ngInject*/
constructor($http) {
this.$http = $http;
}
getItem(id) {
//make sure you use the back-tick (``) not the single quotes ('')
return this.$http.get(`/api/items/${id}`).then(result => result.data);
}
}
export default ItemService;
Modules
//app/components/item/item.module.js
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import itemDirective from './item.directive';
import ItemService from './item.service';
let itemModule = angular.module('item', [
uiRouter
])
.config(($stateProvider) => {
$stateProvider
.state('item', {
url: '/item/:id',
template: '<item></item>'
});
})
.service('ItemService', ItemService)
.directive('item', itemDirective);
// OR .directive('item', ItemDirective.directiveFactory) -- Directives (2)
export default itemModule;Modules (2)
//app/components/components.module.js
import angular from 'angular';
import Item from './item/item.module';
import Something from './something/something.module';
let componentModule = angular.module('app.components', [
Item.name,
Something.name
]);
export default componentModule;Resources
Using ES6 with Angular 1.x
By Alin Chiuaru
Using ES6 with Angular 1.x
- 108