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