blob: 9b7d58fb38effd8a43ecddc0152339fa296662bc [file] [log] [blame]
Matteo Scandolo4222a432017-01-23 12:18:40 -08001import * as $ from 'jquery';
2import * as _ from 'lodash';
3
4export interface IXosComponentInjectorService {
5 injectComponent(target: string | JQuery, componentName: string, attributes?: any, transclude?: string, clean?: boolean): void;
6 removeInjectedComponents(target: string | JQuery): void;
7}
8
9export 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) => {
Matteo Scandolo837e0cc2017-01-25 11:37:34 -080053 string += `${this.camelToSnakeCase(a)}="${a}"`;
Matteo Scandolo4222a432017-01-23 12:18:40 -080054 return string;
55 }, '');
56 }
57
58 private camelToSnakeCase(name: string): string {
59 return name.split(/(?=[A-Z])/).map(w => w.toLowerCase()).join('-');
60 };
61}