dynamic_directive_srv.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import angular from 'angular';
  2. import coreModule from '../core_module';
  3. class DynamicDirectiveSrv {
  4. /** @ngInject */
  5. constructor(private $compile, private $rootScope) {}
  6. addDirective(element, name, scope) {
  7. const child = angular.element(document.createElement(name));
  8. this.$compile(child)(scope);
  9. element.empty();
  10. element.append(child);
  11. }
  12. link(scope, elem, attrs, options) {
  13. options
  14. .directive(scope)
  15. .then(directiveInfo => {
  16. if (!directiveInfo || !directiveInfo.fn) {
  17. elem.empty();
  18. return;
  19. }
  20. if (!directiveInfo.fn.registered) {
  21. coreModule.directive(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
  22. directiveInfo.fn.registered = true;
  23. }
  24. this.addDirective(elem, directiveInfo.name, scope);
  25. })
  26. .catch(err => {
  27. console.log('Plugin load:', err);
  28. this.$rootScope.appEvent('alert-error', ['Plugin error', err.toString()]);
  29. });
  30. }
  31. create(options) {
  32. const directiveDef = {
  33. restrict: 'E',
  34. scope: options.scope,
  35. link: (scope, elem, attrs) => {
  36. if (options.watchPath) {
  37. let childScope = null;
  38. scope.$watch(options.watchPath, () => {
  39. if (childScope) {
  40. childScope.$destroy();
  41. }
  42. childScope = scope.$new();
  43. this.link(childScope, elem, attrs, options);
  44. });
  45. } else {
  46. this.link(scope, elem, attrs, options);
  47. }
  48. },
  49. };
  50. return directiveDef;
  51. }
  52. }
  53. coreModule.service('dynamicDirectiveSrv', DynamicDirectiveSrv);