AngularJS : How to get ng-repeat directive template before it gets compiled?

江枫思渺然 提交于 2019-12-01 07:55:44

问题


I'm trying to get the initial html template for the ng-repeat directive that is used inside my custom directive which trancludes nested content. But instead the actual html text that was set inside the directive I get either already compiled ng-repeat directive or simply a comment that looks like the following:

<!-- ngRepeat: item in items -->

I already asked that question at github, but unfortunately the answer wasn't very clear for me. Is there a way to get ng-repeat directive template before it gets compiled?

Here's a simple example of what I am trying to achieve (and a plnkr):

app.directive('parent', function() {
  return {
    restrict:'E',
    template:'<div ng-transclude></div>',
    transclude: true,
    priority: 1001,
    scope: true,
    compile: function(element, attrs) {
      console.log(element.html());
      console.log(element);
    }
  };
});
<parent>
  <div ng-repeat="item in items">
    {{item}}
  </div>
</parent>

回答1:


ng-repeat directive has `transclude: "element", and so, when it is compiled, the entire element is taken out of DOM (in preparation for transclusion) and a comment is left.

So, the first console.log(element.html()) won't see anything, since the transclusion of your own directive hasn't happened.

But even if you examine the inner HTML at link-time, the ngRepeat will have been compiled, but its transclusion would not yet happen; it happens later, when scope.$watchCollection of ngRepeat fires.

So, the only way to see the content is to preempt the compilation of ngRepeat. You can either make your parent directive terminal: true, examine the contents and manually re-compile.

You can also add a directive that runs on a repeatable element with higher priority than ngRepeat and get the contents.

(You could even reuse the "ngRepeat" name)

app.directive("ngRepeat", function(){
  return {
    require: "?^parent", // optionally require your parent
    priority: 1010,
    compile: function(tElem){
      var template = tElem.html();
      return function link(scope, element, attrs, ctrls){
         var parentCtrl = ctrls;

         if (!parentCtrl) return;

         // hand it off to the parent controller
         parentCtrl.setTemplate(template);
      }
    }
  }
})

Demo



来源:https://stackoverflow.com/questions/31890510/angularjs-how-to-get-ng-repeat-directive-template-before-it-gets-compiled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!