213

私がやっていることの非常に煮詰めたバージョンがあり、問題を解決しています。

私はシンプルdirectiveです。要素をクリックするたびに、別の要素が追加されます。ただし、正しくレンダリングするには、最初にコンパイルする必要があります。

私の研究は私をに導きました$compile。しかし、すべての例は複雑な構造を使用しており、ここでの適用方法がよくわかりません。

フィドルはこちら: http://jsfiddle.net/paulocoelho/fBjbP/1/

そしてJSはここにあります:

var module = angular.module('testApp', [])
    .directive('test', function () {
    return {
        restrict: 'E',
        template: '<p>{{text}}</p>',
        scope: {
            text: '@text'
        },
        link:function(scope,element){
            $( element ).click(function(){
                // TODO: This does not do what it's supposed to :(
                $(this).parent().append("<test text='n'></test>");
            });
        }
    };
});

Josh David Millerによるソリューション: http://jsfiddle.net/paulocoelho/fBjbP/2/

4

7 に答える 7

262

そこには無意味な jQuery がたくさんありますが、この場合の $compile サービスは実際には非常に単純です。

.directive( 'test', function ( $compile ) {
  return {
    restrict: 'E',
    scope: { text: '@' },
    template: '<p ng-click="add()">{{text}}</p>',
    controller: function ( $scope, $element ) {
      $scope.add = function () {
        var el = $compile( "<test text='n'></test>" )( $scope );
        $element.parent().append( el );
      };
    }
  };
});

いくつかのベスト プラクティスに従うために、ディレクティブもリファクタリングしたことに気付くでしょう。ご不明な点がございましたら、お気軽にお問い合わせください。

于 2013-03-07T18:51:22.860 に答える
5

Josh David Miller が受け入れた回答は、 inline を使用するディレクティブを動的に追加しようとしている場合に最適ですtemplate。ただし、ディレクティブがtemplateUrl彼の答えを利用する場合は機能しません。これが私のために働いたものです:

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {}, 
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        },
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                    $scope.$digest();
                    $element.find('.modal-body').append(el);
                }, 0);
            }
        }
    }
}]);
于 2015-06-25T06:36:49.297 に答える
5

Josh David Miller は正しいです。

PCoelho さん、$compile舞台裏で何をしているのか、ディレクティブから HTML 出力がどのように生成されるのか知りたい場合は、以下をご覧ください。

このサービスは、ディレクティブ (要素として「test」) を含む$compileHTML( ) のフラグメントをコンパイルし、関数を生成します。"< test text='n' >< / test >"次に、この関数をスコープで実行して、「ディレクティブからの HTML 出力」を取得できます。

var compileFunction = $compile("< test text='n' > < / test >");
var HtmlOutputFromDirective = compileFunction($scope);

完全なコード サンプルの詳細: http://www.learn-angularjs-apps-projects.com/AngularJs/dynamically-add-directives-in-angularjs

于 2015-03-15T21:33:24.123 に答える
4

以前の回答の多くから着想を得て、他のディレクティブに置き換える次の「stroman」ディレクティブを思いつきました。

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

重要:で使用するディレクティブを登録しますrestrict: 'C'。このような:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

次のように使用できます。

<stroman class="my-directive other-class" randomProperty="8"></stroman>

これを取得するには:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

プロティップ。クラスに基づくディレクティブを使用したくない場合は、'<div></div>'好きなものに変更できます。たとえば、代わりに目的のディレクティブの名前を含む固定属性がありますclass

于 2015-07-14T17:34:41.337 に答える