Last active
November 25, 2015 06:59
-
-
Save b1ff/4621c20e5ea705a0f788 to your computer and use it in GitHub Desktop.
A OO wrapper for Angular directives. Encapsulates best practises.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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