Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@b1ff
Last active November 25, 2015 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b1ff/4621c20e5ea705a0f788 to your computer and use it in GitHub Desktop.
Save b1ff/4621c20e5ea705a0f788 to your computer and use it in GitHub Desktop.
A OO wrapper for Angular directives. Encapsulates best practises.
// utility
export function mapToAngular(comp: new() => Component) {
return function dirFactory($injector) {
var instance = $injector.instantiate(comp);
return {
templateUrl: instance.templateUrl,
controller: () => instance,
controllerAs: 'vm',
bindToController: true,
scope: instance.binding,
link: (elm, scope, attrs) => {
//TODO: validation, one way binding?
instance.rendered(elm, scope, attrs);
}
}
}
}
export class Component {
templateUrl: string;
binding: any;
constructor(templateUrl, binding) {
this.templateUrl = templateUrl;
this.binding = binding;
}
rendered(elm, scope, attrs) {}
static register<T extends Component>(name, ctor: new() => T) {
var factory = mapToAngular(ctor);
angular.module('tstest').directive(name, factory);
}
}
// ==== Usage
export class MyComp extends Component {
parameter: number;
plainText: string;
constructor() {
super('app/template.html', {
parameter: '=', // here we might want to extend bindings with types, to support runtime parameters validation
plainText: '@'
});
}
rendered() {
console.log(this.parameter);
console.log(this.plainText);
}
}
Component.register("prefixMyComp", MyComp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment