1

Angular.js に新しい要素を作成したい

<link url="http://google.com">google</link>

それはタグに変換され<a>ます。どうすればこれを行うことができますか?

これまでのコード:

var app = angular.module('app', []);
app.directive('link', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: false,
        template: '<a href="" ng-transclude></a>';
    }
});

しかし、リンクの後にGoogleをレンダリングし、URLを取得する方法がわかりません.

4

1 に答える 1

4

リンク機能で取得できます。ディレクティブは次のようになります。

app.directive('link', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: false,
        template: '<a href="{{url}}" ng-transclude></a>',
        link: function(scope, element, attrs) {
            scope.url = attrs.url;
        }
    }
});

ディレクティブの分離スコープを作成しても問題ない場合は、次のようにすることもできます。

app.directive('link', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: {
            url: '@'
        },
        template: '<a href="{{url}}" ng-transclude></a>'
    }
});

次に、url 属性が自動的にディレクティブのスコープに入れられます。

于 2013-08-15T14:50:40.407 に答える