AngularJS:如何将指令编译为另一个指令?

时间:2014-05-30 16:22:06

标签: javascript angularjs angularjs-directive angularjs-compile

我有编译

的Angular指令
  1. <greeting /><print-greeting />

  2. <print-greeting />Hello World!

  3. 如何将greeting标记放入我的HTML并将其编译为print-greeting,然后最终显示Hello World!?它目前在将其转换为print-greeting后停止。

    以下是我的代码:Plunker


    从以上plunker复制的指令:

    greeting指令

    // Transforms <greeting /> into <print-greeting />
    app.directive("greeting", function ($compile) {
      return {
        restrict: 'E',
          priority: 2,
          compile: function ($templateElement, $templateAttributes) {
    
          var template = '<print-greeting />';
          $templateElement.replaceWith(template);
    
          return function LinkingFunction($scope, $element, $attrs) { };
        }
      };
    });
    

    print-greeting指令

    // Transforms <print-greeting /> into "Hello World!"
    app.directive("printGreeting", function ($compile) {
      return {
        restrict: 'E',
        priority: 1,
        compile: function ($templateElement, $templateAttributes) {
          var template = 'Hello World!';
           $templateElement.replaceWith(template);
    
           return function LinkingFunction($scope, $element, $attrs) { };
         }
      };
    });
    

1 个答案:

答案 0 :(得分:1)

您正在对已编译的模板进行更改。为了使辅助指令得到编译,您需要重新编译:

return function LinkingFunction($scope, $element, $attrs) {
    $compile($element);
};

Fork of your Plunker