plugin_directive_loader.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. ///<reference path="../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import coreModule from '../core_module';
  5. function pluginDirectiveLoader($compile, datasourceSrv) {
  6. function getPluginComponentDirective(options) {
  7. return function() {
  8. return {
  9. templateUrl: options.Component.templateUrl,
  10. restrict: 'E',
  11. controller: options.Component,
  12. controllerAs: 'ctrl',
  13. bindToController: true,
  14. scope: options.bindings,
  15. link: (scope, elem, attrs, ctrl) => {
  16. if (ctrl.link) {
  17. ctrl.link(scope, elem, attrs, ctrl);
  18. }
  19. }
  20. };
  21. };
  22. }
  23. function getModule(scope, attrs) {
  24. switch (attrs.type) {
  25. case "metrics-query-editor":
  26. let datasource = scope.target.datasource || scope.ctrl.panel.datasource;
  27. return datasourceSrv.get(datasource).then(ds => {
  28. if (!scope.target.refId) {
  29. scope.target.refId = 'A';
  30. }
  31. return System.import(ds.meta.module).then(dsModule => {
  32. return {
  33. name: 'metrics-query-editor-' + ds.meta.id,
  34. bindings: {target: "=", panelCtrl: "="},
  35. attrs: {"target": "target", "panel-ctrl": "ctrl"},
  36. Component: dsModule.MetricsQueryEditor
  37. };
  38. });
  39. });
  40. case 'datasource-config-view':
  41. return System.import(scope.datasourceMeta.module).then(function(dsModule) {
  42. return {
  43. name: 'ds-config-' + scope.datasourceMeta.id,
  44. bindings: {meta: "=", current: "="},
  45. attrs: {meta: "datasourceMeta", current: "current"},
  46. Component: dsModule.ConfigView,
  47. };
  48. });
  49. }
  50. }
  51. function appendAndCompile(scope, elem, componentInfo) {
  52. console.log('compile', elem, componentInfo);
  53. var child = angular.element(document.createElement(componentInfo.name));
  54. _.each(componentInfo.attrs, (value, key) => {
  55. child.attr(key, value);
  56. });
  57. $compile(child)(scope);
  58. elem.empty();
  59. elem.append(child);
  60. }
  61. function registerPluginComponent(scope, elem, attrs, componentInfo) {
  62. if (!componentInfo.Component.registered) {
  63. var directiveName = attrs.$normalize(componentInfo.name);
  64. var directiveFn = getPluginComponentDirective(componentInfo);
  65. coreModule.directive(directiveName, directiveFn);
  66. componentInfo.Component.registered = true;
  67. }
  68. appendAndCompile(scope, elem, componentInfo);
  69. }
  70. return {
  71. restrict: 'E',
  72. link: function(scope, elem, attrs) {
  73. getModule(scope, attrs).then(function (componentInfo) {
  74. registerPluginComponent(scope, elem, attrs, componentInfo);
  75. });
  76. }
  77. };
  78. }
  79. coreModule.directive('pluginDirectiveLoader', pluginDirectiveLoader);