2

私は、特別な XML を入力として HTML をレンダリングするプロジェクトに取り組んでいます。私はすでに基本的なケースで成功しています。例えば:

<mybutton name="layla"></mybutton>

に変換されます

<div class="btn">Layla</div>

のようなディレクティブを使用して

.directive('mybutton', function() {
    return {
        restrict: 'E',
        scope: {
            name: '@'
        },
        templateUrl: 'uicomponents/uiButton.html'
    }
})

私が受け取る実際の XML 入力は次のとおりです。

<ui type="back_button" x="10.0" y="630.0"/>

XML 構文の変更は避けたいのですが、必要に応じて変更できます。すべての画面コンポーネントは<ui></ui>タグにあります。type属性はコンポーネントを定義します。

この種のタグのディレクティブをどのように記述しますか? <ui>要素に対して 1 つの巨大なディレクティブを作成し、属性に対して長い switch-case を内部に持つことは賢明ではないようです。

4

2 に答える 2

5

type 属性に基づいて要素を変換し、要素を再コンパイルする ui ディレクティブを作成できます。次のようになります。

app.directive('ui',function($compile){
  return {
    restrict:'E',
    compile:function(tElement,tAttrs){
      if(tAttrs.type){
        tElement.attr(tAttrs.type,'');
        tElement.removeAttr('type');
        return function(scope,el){
          $compile(el)(scope);
        }
      }

    }  
  }
});


app.directive('backButton',function(){
  return {
    replace:true,
    template:'<button ng-click="btnClick()">A back-button template</button>'
  }
});

編集: 私の元の例では、テンプレート要素をコンパイルするのを間違えました - ディレクティブが ngRepeat で使用されている場合、これは機能しません。修正は簡単です。代わりに link 要素をコンパイルします。コードと例を更新しました。

このplnkrの例をチェックしてください。

于 2013-04-10T18:04:49.180 に答える
2

属性の値にバインドされたディレクティブを作成する方法を認識していませんが、以前の SO の回答: Custom Input Typesを参照してください。

アイデアは、ディレクティブのコンパイル機能を使用して、属性の値に応じて異なるテンプレートを作成することです。最初にすべてのカスタム入力テンプレートをキャッシュに入れることができます (必須ではありません)。

angular.module('myapp', ['myapp.directives'])
    .run(['$http', '$templateCache', function($http, $templateCache) {
        $templateCache.put('span.html', '<span>text</span>');
        $http.get('back_button.html', {cache:$templateCache});
    }]);

type 属性に従ってキャッシュから入力テンプレートを取得します。

angular.module('myapp.directives', [])
    .directive('ui', ['$templateCache', function($templateCache) {
        return {
            restrict: 'E',
            compile: function(elem, attrs)
            {
                var type = attrs.type || 'span.html'; // default value ?
                elem.replaceWith($templateCache.get(type));
            }
        }
    }]);

このコードはテストされていません。

編集:これは、テンプレートをプリロードせずに $compile でリンク関数を使用しても機能すると思いますが、それでもそれらをキャッシュします:

angular.module('myapp.directives', [])
    .directive('ui', ['$http', '$templateCache', '$compile', function($http, $templateCache, $compile) {
        return {
            restrict: 'E',
            link: function(scope, elem, attrs)
            {
                var type = attrs.type || 'span.html'; // default value ?
                $http.get('views/' + type + '.html', {cache: $templateCache}).then(function(result) {
                    elem.replaceWith($compile(result.data)(scope));
                });
            }
        }
    }]);

このコードは私のために働いた。

于 2013-04-10T17:47:19.607 に答える