using ng-include along with $templateCache not finding file

1.6k views Asked by At

I have a directive, where I'm trying to dynamically load different partials depending on an object that is injected into directive

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) { ... } 
}

I'm using grunt-html2js to convert all html files to be added to $templateCache. I have verified that the html file is in added to $templateCache, however when I load the page it is having difficulty finding only the .html files that are referenced in the template function.

Is this a timing issue of any sort? Is there a better way to use the template function?

1

There are 1 answers

1
user12121234 On BEST ANSWER

ng-include argument needs to evaluate to URL. I'd do the following, which will be dynamic as the scope variable changes (using the ng-if directive will conditionally switch between views):

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) { ... } 
}

An alternative way of doing this, which opens up a lot more options, is to compile in the link function:

<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);
}