简体   繁体   English

AngularJS:无法弄清楚为什么在使用transclude:'element'进行转换时嵌套的角度指令不被渲染

[英]AngularJS : Can't figure out why nested angular directive does not get rendered when transcluding with transclude:'element'

I have this custom directive called 'panel'. 我有一个名为“ panel”的自定义指令。

<panel title="One Title">
    One Body
    <panel title="Two Title">two</panel>
</panel>

My issue is that I cannot get the nested panel directive to render. 我的问题是我无法获取嵌套面板指令进行渲染。 Please see the plunkr http://plnkr.co/edit/D0LfQqBViuraSNfmym4g?p=preview for the javascript. 请查看plunkr http://plnkr.co/edit/D0LfQqBViuraSNfmym4g?p=preview以获取JavaScript。

I expect 我预计

<div>
    <h1>One Title</h1>
    <div>
        One Body
        <div>
            <h1>Two Title</h1>
             <div>Two Body</div>
            </div>
        </div>
    </div>
</div>

but instead I get 但是我得到了

<div>
    <h1>One Title</h1>
    <div>One Body</div>
</div>

As you will see, my aim is to render the output from data provided from the controller instead of manipulating the dom. 正如您将看到的,我的目的是从控制器提供的数据渲染输出,而不是操纵dom。 I'm exploring the use of directives as just a means of collecting the data and providing it to the controller, so that the template can then just be rendered from data provided by the controller. 我正在探索将指令用作收集数据并将其提供给控制器的一种方法,以便可以从控制器提供的数据中渲染模板。 As a result, I'm looking for a solution that does not use ng-transclude on a div but instead uses some combination of $compile and or transclude(scope, fun...) to achieve the stated goal. 结果,我正在寻找一个不在div上使用ng-transclude而是使用$ compile和或transclude(scope,fun ...)的组合来实现所述目标的解决方案。 My aim is also in the process to better understand how $compile and transclude(scope, fun...) can be effectively used. 我的目的还在于更好地了解$ compile和transclude(scope,fun ...)如何有效使用。

This isn't going to be simple, since you are willing to rely on the ng-bind-html . 这不会很简单,因为您愿意依靠ng-bind-html

Lets look at this first: 让我们先来看一下:

transclude(scope, function(clone, scope){
  panelCtrl.setBody($sce.trustAsHtml(clone.html()));  
});

The clone in the above function will contain a comment placeholder of a child panel directive like this: 上面函数中的clone将包含子panel指令的注释占位符,如下所示:

One Body
<!-- panel: undefined -->

This is because the child panel directive have transclude: 'element' , and its link function hasn't been run yet. 这是因为子面板指令已transclude: 'element' ,并且其链接功能尚未运行。

To fixed this is easy, just modify the code a bit: 要解决这个问题很容易,只需稍微修改一下代码即可:

var clone = transclude(scope, function () {});
panelCtrl.setBody($sce.trustAsHtml(clone.html()));

This way the clone will contain a real template like this: 这样, clone将包含一个真实的模板,如下所示:

One Body
<div class="ng-scope"><h1 class="ng-binding">{{panel.title}}</h1><div class="inner ng-binding" ng-bind-html="panel.body"></div></div>

Not so surprise, we now have a real template, but the bindings haven't happened yet, so we still can't use clone.html() at this time. 并不奇怪,我们现在有了一个真实的模板,但是绑定尚未发生,因此我们目前仍不能使用clone.html()

And the real problem begin: How can we know when the bindings will be finished 真正的问题开始了: 我们如何知道绑定何时完成

AFAIK, we can't know when exactly. AFAIK,我们不知道确切的时间。 But to workaround this we can use $timeout ! 但是要解决此问题,我们可以使用$timeout

By using $timeout , we are breaking a normal compilation cycle, so we have to find some way to let parent panel directive know that the binding of child directives have been finished (in $timeout ). 通过使用$timeout ,我们打破了正常的编译周期,因此我们必须找到某种方法让父面板指令知道子指令的绑定已经完成(在$timeout )。

One way is using controllers for communication and the final code will look like this: 一种方法是使用控制器进行通信,最终代码如下所示:

app.controller('PanelCtrl', function($scope, $sce) {    
  $scope.panel = {
    title: 'ttt',
    body: $sce.trustAsHtml('bbb'),
  }

  this.setTitle = function(title) {
    $scope.panel.title = title;
  };

  this.setBody = function(body) {
    $scope.panel.body = body;
  };

  var parentCtrl,
      onChildRenderedCallback,
      childCount = 0;

  this.onChildRendered = function(callback) {
    onChildRenderedCallback = function () {
      callback();

      if (parentCtrl) {
        $timeout(parentCtrl.notify, 0);
      }
    };

    if (!childCount) {
      $timeout(onChildRenderedCallback, 0);
    }
  };

  this.notify = function() {
    childCount--;

    if (childCount === 0 && onChildRenderedCallback) {
      onChildRenderedCallback();
    }
  };

  this.addChild = function() {
    childCount++;
  };

  this.setParent = function (value) {
    parentCtrl = value;
    parentCtrl.addChild(this);
  };
});

app.directive('panel', function($compile, $sce, $timeout) {
  return {
    restrict: 'E',
    scope: {},
    replace: true,
    transclude: 'element',
    controller: 'PanelCtrl',
    require: ['panel', '?^panel'],
    link: function(scope, element, attrs, ctrls, transclude) {
      var panelCtrl = ctrls[0];
      var parentCtrl = ctrls[1];

      if (parentCtrl) {
        panelCtrl.setParent(parentCtrl);
      }

      var template =
        '<div>' +
        '  <h1>{{panel.title}}</h1>' +
        '  <div class="inner" ng-bind-html="panel.body"></div>' +
        '</div>';

      var templateContents = angular.element(template);
      var compileTemplateContents = $compile(templateContents);
      element.replaceWith(templateContents);

      panelCtrl.setTitle(attrs.title);

      var clone = transclude(scope, function () {});

      panelCtrl.onChildRendered(function() {
        panelCtrl.setBody($sce.trustAsHtml(clone.html()));
        compileTemplateContents(scope);
      });
    }
  }
});

Example Plunker: http://plnkr.co/edit/BBbWsUkkebgXiAdcnoYE?p=preview 柱塞示例: http ://plnkr.co/edit/BBbWsUkkebgXiAdcnoYE?p=preview

I've left a lot of console.log() in the plunker, you could have a look to see what are really happen. 我在插件中留了很多console.log() ,您可以看看实际发生了什么。

PS. PS。 Things will be a lot easier if you don't use ng-bind-html and just allow DOM manupulations or using something like in @WilliamScott's answer. 如果您不使用ng-bind-html而只允许DOM操作或使用@WilliamScott的答案中的类似内容,则事情会容易得多。

Simplifying the directive results in what I think you're going for: 简化指令会导致我认为您想要的是:

app.directive('panel', function(){
  return {
    restrict: 'E',
    template:'<div><h1>{{panel.title}}</h1><div ng-transclude></div></div>',
    scope: {},
    transclude: true,
    controller: 'PanelCtrl',
    link: function(scope, element, attrs, panelCtrl)
    {
      panelCtrl.setTitle(attrs.title);
    }
  }  
})

Here's a plunkr . 这是一个笨拙的人

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

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