如何指定我想要转换指令的父级?

时间:2017-04-07 13:33:30

标签: angularjs angular-material

我有一个灯箱指令,当它转换时,它会注入内容。从技术上讲,无论我将实际调用放在指令中。但实质上,我需要它转换到正文,以便背景可以覆盖整个页面视口,并使其居中到视口,而不是容器现在转录到。

该指令以这种方式编写:

(function() {
    'use strict';

    angular
        .module('app.core')
        .directive('lightboxDirective', lightboxDirective);

        function lightboxDirective() {
            return {
              restrict: 'E',
              transclude: true,
              scope: {},
              template: '<section class="md-lightbox" ng-transclude></section>',
            };
        }

})();

灯箱以这种方式位于页面中:

<div id="scala-media-media" class="page-layout">
     <div class="center" flex>
          <div class="header">
               <img ng-src="{{vm.media.images[0].url}}" ng-click="showLightBox = true">
          </div>
          <div class="content">
               ... the page content here ...
          </div>
     </div>
</div>

<lightbox-directive class="angular-lightbox" ng-class="{ removed : !showLightBox }">
      ... the code for my lightbox content (which works fine by the way) ...
</lightbox-directive>

起初我以为我会在{mdDialog(Angular Material)中使用parent: angular.element($document.body),来指定父级,但这并不成功。 parent不是我认为的公认回调。

注意图像注入的位置。就在我放置的地方!如果我可以将代码放在那里并且在没有指令的情况下执行相同的操作,那么使用指令有什么意义呢?对? dev tool screenshot

以下是正在发生的事情的屏幕截图。请注意我在左侧的背景和居中问题,而不是我想要的右侧对话框。 enter image description here

我正在使用此CODEPEN

中的角度灯箱

更新

我将灯箱移动到了自己的模板文件中,以免直接在页面上使用代码而感到内疚,这使得指令的使用变得多余。并重新构建了我的指令,如下所示。但是在运行时渲染仍然是一个问题。模板注入调用的位置。现在,如果我只能将身体声明为其附加的父亲!洛尔

新指令:

function lightboxDirective() {
    return {
        restrict: 'E',
        templateUrl: function(elem,attrs) {
            return attrs.templateUrl || 'app/main/pages/scala-media/views/lightbox-template.html'
        }
    };
}

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用

在关闭body标记之前重新定位元素
.directive("lightboxDirective", function() {
  return {
    restrict: 'E',
    transclude: true,
    scope: {},
    template: '<section class="md-lightbox" ng-transclude></section>',
    link: function(scope, elem) {
      angular.element(document).find("body").append(elem);
    }
  };
});
相关问题