3

問題

カスタム ディレクティブを介してng-bind属性を動的に追加し、どこでもテンプレート定義に手動で追加することなく、カスタム ディレクティブでng-bind、ng-bind-html、またはng-bind-html-unsafeを使用できるようにします。

http://jsfiddle.net/nstuart/hUxp7/2/

壊れたディレクティブ

angular.module('app').directive('bindTest', [
'$compile',
function ($compile) {
    return {
        restrict: 'A',
        scope: true,
        compile: function (tElem, tAttrs) {
            if (!tElem.attr('ng-bind')) {
                tElem.attr('ng-bind', 'content');
                $compile(tElem)
            }
            return function (scope, elem, attrs) {
                console.log('Linking...');
                scope.content = "Content!";
            };
        }
    };
}]);

解決

わかりません。上記のフィドルのようなものが機能しない理由が本当にわかりません。そこに余分な$compileがある場合とない場合で試してみました。

回避策

ディレクティブにテンプレート値を追加することで回避できますが、それはコンテンツを余分な div でラップするため、可能であればそれを可能にしたいと考えています。(フィドルを参照)

2 番目の回避策

ここでフィドルを参照してください: http://jsfiddle.net/nstuart/hUxp7/4/ (以下のイカルス博士の提案による)。リンク機能に到達する前にテンプレートを変更し、変更を見つけて適用する必要があるように感じるので、これを現在の回避策と考えています。

4

4 に答える 4

2

次のように、リンク関数内でコンパイル部分を実行できます。

angular.module('app').directive('bindTest', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        scope: true,
        link: {
            post: function(scope, element, attrs){
                if (!element.attr('ng-bind')) {
                    element.attr('ng-bind', 'content');
                    var compiledElement = $compile(element)(scope);
                }
                console.log('Linking...');
                scope.content = "Content!";                
            }
        }
    };
}]);

これがどれだけうまくいったか教えてくださいhttp://jsfiddle.net/bPCFj/

于 2013-03-12T00:43:10.470 に答える
2

この方法はより洗練されており ($compile との依存関係はありません)、あなたのケースに適しています:

angular.module('app').directive('myCustomDirective', function () {
    return {
        restrict: 'A',
        scope: {},
        template: function(tElem, tAttrs) {
            return tAttrs['ng-bind'];
        },
        link: function (scope, elem) {
            scope.content = "Happy!";
        }
    };
});

jsFiddle : http://jsfiddle.net/hUxp7/8/

Angularディレクティブのドキュメントから: テンプレートを表す文字列として、または2つの引数tElementとtAttrs(以下のコンパイル関数APIで説明)を取り、テンプレートを表す文字列値を返す関数としてテンプレートを指定できます。

于 2014-01-26T23:29:27.330 に答える
1

あなたたちはとても近かった。

function MyDirective($compile) {
    function compileMyDirective(tElement) {
        tElement.attr('ng-bind', 'someScopeProp');

        return postLinkMyDirective;
    }

    function postLinkMyDirective(iScope, iElement, iAttrs) {
        if (!('ngBind' in iAttrs)) {
            // Before $compile is run below, `ng-bind` is just a DOM attribute
            // and thus is not in iAttrs yet.
            $compile(iElement)(iScope);
        }
    }

    var defObj = {
        compile: compileMyDirective,
        scope: {
            someScopeProp: '=myDirective'
        }
    };

    return defObj;
}

結果は次のようになります。

<ANY my-directive="'hello'" ng-bind="someScopeProp">hello</ANY>
于 2015-08-07T00:44:20.120 に答える