从指令添加指令的通用方法

时间:2016-12-14 20:33:06

标签: angularjs angularjs-directive

我试图编写一个Angular 1指令,该指令将动态地向该元素添加其他指令。这些其他指令非常复杂,我不想将其代码复制并粘贴到此meta指令中。我创建了一个plnkr,展示了我想要完成的任务here

这是指令

的副本
function myCustomAttribute($compile) {
  var priority = 1001; // greater than ng-repeat
  return {
    restrict: 'A',
    compile: compile,
    priority: priority,
    terminal: true,
  };

  function compile(templateElement, templateAttributes, transcludeFn) {
    var attrValue = templateAttributes[attributeDirectiveName];
    templateAttributes.$set(colorDirectiveName, attrValue);

    var compiled = $compile(templateElement, transcludeFn, priority);
    return function linkFn(scope) {
      compiled(scope);
    };
  }

  function doubleCompile(templateElement, templateAttributes, transcludeFn) {
    var attrValue = templateAttributes[attributeDirectiveName];
    templateAttributes.$set(colorDirectiveName, attrValue);
    templateElement.removeAttr('my-custom-attribute');

    return function linkFn(scope, element, attrs, ctrls, transcludeFn) {
        $compile(element, transcludeFn)(scope);
    };
  }
}

compile功能来自angular documentation on the double compilation issue。正如plnkr所示,当与具有transclude: true和隔离范围的指令一起使用时,它会出现问题。它在嵌套的ng-repeat中也存在问题。

doubleCompile函数来自Add directives from directive in AngularJS。正如plnkr所示,它存在具有更高优先级的双重编译指令的问题。它也有相同的转录问题。

plnkr是我在我的应用程序中试图解决的一个缩小的例子,除了myCustomAttribute指令之外的所有代码都用于突出显示问题。如何更新myCustomAttribute以使其适用于所有情况?

0 个答案:

没有答案