dynamic_directive_srv.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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(attrs.$normalize(directiveInfo.name), directiveInfo.fn);
  23. directiveInfo.fn.registered = true;
  24. }
  25. this.addDirective(elem, directiveInfo.name, scope);
  26. })
  27. .catch(err => {
  28. console.log('Plugin load:', err);
  29. this.$rootScope.appEvent('alert-error', ['Plugin error', err.toString()]);
  30. });
  31. }
  32. create(options) {
  33. let directiveDef = {
  34. restrict: 'E',
  35. scope: options.scope,
  36. link: (scope, elem, attrs) => {
  37. if (options.watchPath) {
  38. let childScope = null;
  39. scope.$watch(options.watchPath, () => {
  40. if (childScope) {
  41. childScope.$destroy();
  42. }
  43. childScope = scope.$new();
  44. this.link(childScope, elem, attrs, options);
  45. });
  46. } else {
  47. this.link(scope, elem, attrs, options);
  48. }
  49. },
  50. };
  51. return directiveDef;
  52. }
  53. }
  54. coreModule.service('dynamicDirectiveSrv', DynamicDirectiveSrv);