0

ディレクティブに注入されたオブジェクトに応じて、異なるパーシャルを動的にロードしようとしているディレクティブがあります。

function countSummary() {
    var directive = {
        scope: {
            countData: '='
        },
        link: link,
        template: '<div ng-include=\'countData.countType === "expected" ? ' +                         '"/app/count/countsummary/countExpected.html" :' +
                   '"/app/count/countsummary/countBlind.html"\'>' +
                   '</div>'
    }
    return directive;

    function link(scope, element, attrs) { ... } 
}

grunt-html2jsに追加するすべてのhtmlファイルを変換するために使用しています$templateCache。html ファイルが に追加されていることを確認しましたが、ページをロードすると、関数で参照されているファイル$templateCacheだけを見つけるのが困難です。.htmltemplate

これは何らかのタイミングの問題ですか?テンプレート機能を使用するより良い方法はありますか?

4

1 に答える 1

1

ng-include 引数は URL に評価される必要があります。スコープ変数が変更されると動的になります( ng-if ディレクティブを使用すると、条件付きでビューが切り替わります):

function countSummary() {
  var directive = {
    scope: {
      countData: '='
    },
    link: link,
    template: '<div ng-if="countData.countType === \'expected\'" ng-include="\'/app/count/countsummary/countExpected.html\'"></div>' +
    '<div ng-if="countData.countType !== \'expected\'" ng-include="\'/app/count/countsummary/countBlind.html\'"></div>'
  }
  return directive;

  function link(scope, element, attrs) { ... } 
}

これを行う別の方法は、リンク関数でコンパイルすることです。これにより、より多くのオプションが開かれます。

<script type="text/ng-template" id="my_template_1">
  <div ng-if="countData.countType === 'expected'" ng-include="/app/count/countsummary/countExpected.html"></div>
  <div ng-if="countData.countType !== 'expected'" ng-include="/app/count/countsummary/countBlind.html"></div>
</script>

function link(scope, element, attrs) {

  var html = $templateCache.get('my_template_1');

  // parse HTML into DOM element
  var template = angular.element( html );

  // compile the template
  var linkFn = $compile(template);

  // link the compiled template with the scope
  var el = linkFn(scope);

  // append to DOM
  element.appendChild(el);
}
于 2015-08-14T15:24:26.447 に答える