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,但是当我加载页面时,很难仅找到函数.html中引用的文件template

这是任何时间问题吗?有没有更好的方法来使用模板功能?

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 回答