Last active
July 13, 2016 16:01
-
-
Save vsternbach/b7a4162c5c3f9ca4608743ad4a7b7dba to your computer and use it in GitHub Desktop.
angularjs typescript decorators
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
const ngApp = 'app'; | |
//import {ngApp} from "./constants"; | |
const module = function(moduleOrName) { | |
return typeof moduleOrName === "string" | |
? angular.module(moduleOrName) | |
: moduleOrName; | |
}; | |
export function Component(options: { | |
selector: string, | |
controllerAs?: string, | |
template?: string, | |
templateUrl?: string, | |
bindings? : any | |
}, moduleOrName: string | ng.IModule = `${ngApp}.components`) { | |
return (controller: any) => { | |
const selector = options.selector; | |
delete options.selector; | |
module(moduleOrName).component(selector, angular.extend(options, { controller: controller })); | |
} | |
} | |
export function Service(moduleOrName: string | ng.IModule = `${ngApp}.services`) { | |
return (service: any) => { | |
const name = service.name; | |
const isProvider = service.hasOwnProperty('$get'); | |
if (!name) { | |
console.error('Service decorator can be used with named class only'); | |
} | |
module(moduleOrName)[isProvider ? 'provider' : 'service'](name, service); | |
} | |
} | |
interface PipeTransformStatic { | |
new(...args: any[]): PipeTransform; | |
} | |
export interface PipeTransform { | |
transform(value: any, ...args: any[]): any; | |
} | |
export function Pipe(options: {name: string}, moduleOrName: string | ng.IModule = `${ngApp}.pipes`) { | |
return (Pipe: PipeTransformStatic) => { | |
const filter = () => { | |
const $injector = angular.injector(['ng']); | |
const instance:any = $injector.instantiate(Pipe); | |
return instance.transform.bind(instance); | |
}; | |
module(moduleOrName).filter(options.name, filter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment