AngularJS - 转换多个指令

时间:2014-09-30 15:45:50

标签: angularjs angularjs-directive

我有一种情况需要在我的外部指令中转换多个子指令。我已经有了它的工作,但我想知道是否有更好的,更多的角度"这样做的方法?

工作示例如下:http://plnkr.co/edit/pmukXJPxUGd2gnMvEN1a?p=preview

Plunker代码:

<!DOCTYPE html>
<html>

  <head>
    <script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>

  <body ng-app="myApp">

    <outer-directive>
      <inner-directive1>Some Html I want placed elsewhere</inner-directive1>
      <inner-directive2>Yet more Html that should be somewhere else</inner-directive2>
    </outer-directive>

    <script>
      var app = angular.module("myApp", []);

      app.directive("outerDirective", function($compile) {
        return {
          restrict: 'E',
          transclude: true,
          scope: {},
          template: '<div>' +
                    '  <h1>This is a title</h1>' +
                    '  <div class="inner1"></div><br />' +
                    '  Some other code that is in the directive<br /><br />' +
                    '  <div class="inner2"></div><br />' +
                    '</div>',
          link: function(scope, element, attrs, emptyCtrl, transclude) {
            transclude(scope, function(clone) {
              clone.each(function (i, ele) {
                if (ele.nodeName === "INNER-DIRECTIVE1") {
                  $(element).find(".inner1").replaceWith($compile(ele)(scope));
                }

                if (ele.nodeName === "INNER-DIRECTIVE2") {
                  $(element).find(".inner2").replaceWith($compile(ele)(scope));
                }
              });
            });
          }
        }
      });
    </script>
  </body>
</html>

0 个答案:

没有答案