在angular指令中获取原始的transcluded内容

时间:2013-11-20 16:56:23

标签: javascript angularjs transclusion

我的目标是创建一个editable指令,允许用户编辑附加了该属性的任何元素的HTML(请参阅Plunker:http://plnkr.co/edit/nIrr9Lu0PZN2PdnhQOC6

几乎有效,但我无法获取已转换内容的原始原始HTML以初始化文本区域。我可以从clone.text()获取该文本,但是缺少<H1><div>等HTML标记,因此点击“应用而不进行编辑”并不是幂等的。

方法clone.html()会抛出错误Cannot read property 'childNodes' of undefined

app.directive("editable", function($rootScope) {
  return {
    restrict: "A",
    templateUrl: "mytemplate.html",
    transclude: true,
    scope: {
      content: "=editContent"
    },

    controller: function($scope, $element, $compile, $transclude, $sce) {

      // Initialize the text area with the original transcluded HTML...
      $transclude(function(clone, scope) {

        // This almost works but strips out tags like <h1>, <div>, etc.
        // $scope.editContent = clone.text().trim();

        // this works much better per @Emmentaler, tho contains expanded HTML
        var html = ""; 
        for (var i=0; i<clone.length; i++) {
            html += clone[i].outerHTML||'';}
        });
        $scope.editContent = html;

      $scope.onEdit = function() {
        // HACK? Using jQuery to place compiled content 
        $(".editable-output",$element).html(
          // compiling is necessary to render nested directives
          $compile($scope.editContent)($rootScope)
        );
      }

      $scope.showEditor = false;

      $scope.toggleEditor = function() {
        $scope.showEditor = !$scope.showEditor;
      }         
    }
  }
});

(这个问题基本上是在早先尝试构建问题之后对问题和代码进行批量重写,Get original transcluded content in Angular directive

1 个答案:

答案 0 :(得分:3)

$element.innerHTML应包含原始HTML。我显示它包含

  <div class="editable">
  <span class="glyphicon glyphicon-edit" ng-click="toggleEditor()"></span>

    <div class="editable-input" ng-show="showEditor">
       <b><p>Enter well-formed HTML content:</p></b>
       <p>E.g.<code>&lt;h1&gt;Hello&lt;/h1&gt;&lt;p&gt;some text&lt;/p&gt;&lt;clock&gt;&lt;/clock&gt;</code></p>
       <textarea ng-model="editContent"></textarea>
       <button class="btn btn-primary" ng-click="onEdit()">apply</button>
    </div>

    <div class="editable-output" ng-transclude=""></div>
  </div>