0

その場でテンプレートを含むディレクティブを実行しようとしましたが、問題が 1 つあります。ng-model を含むすべての属性をコンパイルした後、新しい要素に変換されず、ng-model が機能しません。どこが間違っていますか?

要素コード:

<input type-test="kendo">

指令:

    App.directive('typeTest', ['$templateCache', '$compile', '$http', 'Formatter',
        function ($templateCache, $compile, $http, Formatter) {
            return {
                restrict: 'A',
                scope: {
                    ngModel: '='
                },
                replace: true,
                link: function(scope, element, attrs) {
                    $http.get(Formatter.getTemplateUrl(attrs.typeTest), {cache: $templateCache}).success(function(tplContent) {
                        var el = $compile(tplContent)(scope);
                        element.replaceWith(el);
                    });
                }
            }
        }
    ]);

Formatter.getTemplateUrl() は、入力引数 (attrs.typeTest) に応じてテンプレートへの URL を返します。

type-test="kendo" にするテンプレート:

<input type="text" kendo-drop-down-list k-data-source="list" k-data-text-field="'Name'" k-data-value-field="'Id'">

リストは [{Id: 1, Name: 'First'}, {Id: 2, Name: 'Second'}] のように定義されます。

4

2 に答える 2

0

ディレクティブのリンク関数内の要素を置き換えるべきではありません。リンク関数は、ディレクティブが機能するようにイベント リスナーをセットアップする必要があります。リンク関数ではなく、コンパイル関数内にロジックを配置します。これについてのかなり良い記事があります:http://amitgharat.wordpress.com/2013/06/08/the-hitchhikers-guide-to-the-directive/

于 2014-03-31T07:58:03.320 に答える