dynamic_directive_srv.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import angular from 'angular';
  2. import coreModule from '../core_module';
  3. class DynamicDirectiveSrv {
  4. /** @ngInject */
  5. constructor(private $compile) {}
  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. const directiveInfo = options.directive(scope);
  14. if (!directiveInfo || !directiveInfo.fn) {
  15. elem.empty();
  16. return;
  17. }
  18. if (!directiveInfo.fn.registered) {
  19. coreModule.directive(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
  20. directiveInfo.fn.registered = true;
  21. }
  22. this.addDirective(elem, directiveInfo.name, scope);
  23. }
  24. create(options) {
  25. const directiveDef = {
  26. restrict: 'E',
  27. scope: options.scope,
  28. link: (scope, elem, attrs) => {
  29. if (options.watchPath) {
  30. let childScope = null;
  31. scope.$watch(options.watchPath, () => {
  32. if (childScope) {
  33. childScope.$destroy();
  34. }
  35. childScope = scope.$new();
  36. this.link(childScope, elem, attrs, options);
  37. });
  38. } else {
  39. this.link(scope, elem, attrs, options);
  40. }
  41. },
  42. };
  43. return directiveDef;
  44. }
  45. }
  46. coreModule.service('dynamicDirectiveSrv', DynamicDirectiveSrv);