22

私の目標はeditable、属性が付加された任意の要素の HTML をユーザーが編集できるようにするディレクティブを作成することです (Plunkr: 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.innerHTMLHTML が含まれている必要があります。含まれていることを示しています。

  <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 に答える