dynamic_directive_srv.ts 1.7 KB

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