繁体   English   中英

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

[英]AngularJS : How can I compile a directive as another directive?

我有编译的Angular指令

  1. <greeting /><print-greeting />以及

  2. <print-greeting />Hello World!

我怎样才能在我的HTML中放上greeting标签并将其编译为print-greeting ,然后最终显示Hello World! 当前将其变为print-greeting后停止。

这是我的代码: 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) { };
     }
  };
});

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

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

柱塞的前叉

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM