How to dynamically create a ngInclude directive?

- 1 answer

Ad

When I put this in my HTML, it works fine:

<div ng-include="'my-template.html'"></div>

But when I'm trying to create that ngInclude directive dynamically using jQuery (after the DOM is ready), it does not work:

$(function() {
  var el = document.createElement('div');
  el.setAttribute('ng-include', "'my-template.html'");
  $('.container').replaceWith(el);
});

The element is indeed inserted into the DOM with the expected template, but it's not being interpreted as AngularJS code. No errors in console.

What am I missing?

Ad

Answer

Ad

You will need to compile your HTML

I'm not sure what the syntax is like in your file (whether you're using requireJS or not) but it should be something similar to compiling the new element with the scope.

angular.element('[ng-app]')
       .injector()
       .invoke(['$compile', function ($compile) {
                    var $scope = angular.element(el).scope();
                    $compile(el)($scope);
                    $scope.$apply();
                }]);
Ad
source: stackoverflow.com
Ad