Matteo Scandolo | 4222a43 | 2017-01-23 12:18:40 -0800 | [diff] [blame] | 1 | import * as $ from 'jquery'; |
| 2 | import * as _ from 'lodash'; |
| 3 | |
| 4 | export interface IXosComponentInjectorService { |
| 5 | injectComponent(target: string | JQuery, componentName: string, attributes?: any, transclude?: string, clean?: boolean): void; |
| 6 | removeInjectedComponents(target: string | JQuery): void; |
| 7 | } |
| 8 | |
| 9 | export class XosComponentInjector implements IXosComponentInjectorService { |
| 10 | static $inject = ['$rootScope', '$compile']; |
| 11 | |
| 12 | constructor ( |
| 13 | private $rootScope: ng.IRootScopeService, |
| 14 | private $compile: ng.ICompileService |
| 15 | ) { |
| 16 | } |
| 17 | |
| 18 | public injectComponent(target: string | JQuery, componentName: string, attributes?: any, transclude?: string, clean?: boolean) { |
| 19 | let targetEl; |
| 20 | if (angular.isString(target)) { |
| 21 | targetEl = $(target); |
| 22 | } |
| 23 | else { |
| 24 | targetEl = target; |
| 25 | } |
| 26 | |
| 27 | const componentTagName = this.camelToSnakeCase(componentName); |
| 28 | let scope = this.$rootScope.$new(); |
| 29 | let attr: string = ''; |
| 30 | |
| 31 | if (clean) { |
| 32 | this.removeInjectedComponents(target); |
| 33 | } |
| 34 | |
| 35 | if (angular.isDefined(attributes) && angular.isObject(attributes)) { |
| 36 | attr = this.stringifyAttributes(attributes); |
| 37 | scope = angular.merge(scope, attributes); |
| 38 | } |
| 39 | |
| 40 | const componentTag = `<${componentTagName} ${attr}>${transclude || ''}</${componentTagName}>`; |
| 41 | const element = this.$compile(componentTag)(scope); |
| 42 | |
| 43 | targetEl.append(element); |
| 44 | } |
| 45 | |
| 46 | public removeInjectedComponents(target: string | JQuery) { |
| 47 | const targetEl = $(target); |
| 48 | targetEl.html(''); |
| 49 | } |
| 50 | |
| 51 | private stringifyAttributes(attributes: any): string { |
| 52 | return _.reduce(Object.keys(attributes), (string: string, a: string) => { |
| 53 | string += `${a}="${a}"`; |
| 54 | return string; |
| 55 | }, ''); |
| 56 | } |
| 57 | |
| 58 | private camelToSnakeCase(name: string): string { |
| 59 | return name.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join('-'); |
| 60 | }; |
| 61 | } |