dynamic_directive_srv.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import angular from 'angular';
  2. import coreModule from '../core_module';
  3. class DynamicDirectiveSrv {
  4. /** @ngInject */
  5. constructor(private $compile: angular.ICompileService) {}
  6. addDirective(element: any, name: string, scope: any) {
  7. const child = angular.element(document.createElement(name));
  8. this.$compile(child)(scope);
  9. element.empty();
  10. element.append(child);
  11. }
  12. link(scope: any, elem: JQLite, attrs: any, options: any) {
  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: any) {
  25. const directiveDef = {
  26. restrict: 'E',
  27. scope: options.scope,
  28. link: (scope: any, elem: JQLite, attrs: any) => {
  29. if (options.watchPath) {
  30. let childScope: any = 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);