22

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

几乎可以工作,除非我无法获得转入内容的原始原始 HTML 来初始化文本区域。我可以从中获取它的文本clone.text(),但是缺少 HTML 标签,如<H1>,<div>等,因此单击应用而不进行编辑不是幂等的。

该方法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;
      }         
    }
  }
});

(这个问题本质上是在较早尝试构建问题之后对问题和代码的全面重写,在 Angular 指令中获取原始嵌入内容

4

1 回答 1

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>
于 2013-11-20T18:04:05.427 回答