【问题标题】:AngularJs $transclude - How to access the html content of clone object?AngularJs $transclude - 如何访问克隆对象的 html 内容?
【发布时间】:2014-03-04 21:46:45
【问题描述】:

我正在尝试访问指令中 $transclude 函数内的“克隆”对象的内容,但 clone.html() 返回未定义。如何访问指令元素/克隆的 html 内容?

.directive('somedirective', function(){
    return {
        restrict: 'EA'
        , replace: true
        , transclude: true
        , scope: true
         , controller: function ($scope, $element, $transclude, $log) {
             $transclude(function (clone) {
                 console.log(clone.html()); //undefined??
                 console.log(clone.text()); //works but strips the html tags
                 // How do I access the html content of clone???
                })
             }
         }

SEE PLUNKER

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    你得到了未定义,因为你的克隆实际上是三个元素,text-div-text。因此,删除<drt> and <div> 之间的空格可以解决部分问题,因此“clone.html()”将打印“testing”。问题的第二部分是 .html() 使用“innerHTML”属性,因此它不会包含克隆的根 DOM 元素。相反,请尝试使用clone[0].outerHTMLangular.element("<div/>").append(clone).html()

    http://plnkr.co/edit/mOnlFLJMHkQ0iQIeZTwd?p=preview

    controller: function($scope, $element, $transclude, $log){
     $transclude(function(clone) {
         console.log(clone[0].innerHTML); //undefined??
         console.log(clone[0].outerHTML); //undefined??
         console.log(angular.element("<div/>").append(clone).html()); //undefined??
         console.log(clone.text()); //works but strips the html tags    
      });
    

    【讨论】:

      【解决方案2】:

      我使用以下代码将元素转换为纯 HTML:

      var transcludedHtml = "";  // this var accumulates a result
      $transclude(function(clone) {
        clone.each(function(idx, node) {
          if (node.outerHTML) {
            transcludedHtml += node.outerHTML;
          }
        });
      

      该方法并不完美,因为它会跳过某些类型的节点(例如 HTML 实体等)。但是对于带有标签元素的常规 HTML sn-ps 来说已经足够了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-17
        • 2019-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-12
        相关资源
        最近更新 更多