grafana/public/app/angular/services/dynamic_directive_srv.ts

57 lines
1.5 KiB
TypeScript
Raw Normal View History

2017-12-20 05:33:33 -06:00
import angular from 'angular';
import coreModule from '../core_module';
2016-01-13 07:03:50 -06:00
class DynamicDirectiveSrv {
/** @ngInject */
constructor(private $compile: angular.ICompileService) {}
2016-01-13 07:03:50 -06:00
addDirective(element: any, name: string, scope: any) {
const child = angular.element(document.createElement(name));
this.$compile(child)(scope);
2016-01-13 07:03:50 -06:00
element.empty();
element.append(child);
2016-01-13 07:03:50 -06:00
}
link(scope: any, elem: JQLite, attrs: any, options: any) {
const directiveInfo = options.directive(scope);
if (!directiveInfo || !directiveInfo.fn) {
elem.empty();
return;
}
if (!directiveInfo.fn.registered) {
coreModule.directive(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
directiveInfo.fn.registered = true;
}
this.addDirective(elem, directiveInfo.name, scope);
}
create(options: any) {
const directiveDef = {
2017-12-20 05:33:33 -06:00
restrict: 'E',
2016-01-13 14:07:57 -06:00
scope: options.scope,
link: (scope: any, elem: JQLite, attrs: any) => {
if (options.watchPath) {
let childScope: any = null;
scope.$watch(options.watchPath, () => {
if (childScope) {
childScope.$destroy();
}
childScope = scope.$new();
this.link(childScope, elem, attrs, options);
});
} else {
this.link(scope, elem, attrs, options);
}
2017-12-20 05:33:33 -06:00
},
2016-01-13 14:07:57 -06:00
};
2016-01-13 07:03:50 -06:00
2016-01-13 14:07:57 -06:00
return directiveDef;
2016-01-13 07:03:50 -06:00
}
}
2017-12-20 05:33:33 -06:00
coreModule.service('dynamicDirectiveSrv', DynamicDirectiveSrv);