Silas
Silas

Reputation: 221

AngularJS add ng-include dynamically after app is loaded

I have an update button with a directive. When the button is clicked, the targeted element should receive some new html which includes a ngInclude element. It does not seem to be loading the file though, all it does is include a comment like this <!-- ngInclude: nav.html -->. If I log the tpl variable I get { 0: <!-- ngInclude: nav.html -->, length: 1 }. Here is my directive and element generator code.

Directive

angular.module('myApp').directive("contentControl"
,["$compile"
,function($compile){
    return {
        link: function(scope, element, attrs) {
            element.bind("click", function () {
                var $container = $(this).closest('#editor_contenteditorcontainer');
                var html = "";
                $container.find('.row').each(function () {
                    var $args = $(this).find('form').serializeObject();
                    html += ' ' + generateContent($args);
                });
                angular.element(document.getElementById('responsiveviewport')).html(html);
                $compile(html)(scope);
                scope.$apply();
            });
        }
    }
}]);

Generator

function generateContent($arg){
  switch($arg['name']){
    case 'Partial':
        return '<div ng-include src="\''+$arg['content']+'\'"></div>';
        break;
    default:
        break;
  }
}

Upvotes: 6

Views: 5146

Answers (2)

sbedulin
sbedulin

Reputation: 4342

You would need to compile the place where you inserted generated content.

.directive('contentControl', ['$compile' ,function($compile){
    return {
      template: 'Click here',
      link: function(scope, element, attrs) {
          element.bind('click', function () {
              var html = "<p>Template:</p><div ng-include src=\"'template.html'\"></div>";

              var templateGoesHere = angular.element(document.getElementById('templateGoesHere'));
              templateGoesHere.html(html);

              $compile(templateGoesHere)(scope);

              scope.$apply();
          });
      }
    }
}]);

See Plunker

Upvotes: 6

Sacho
Sacho

Reputation: 2179

$compile(element)(scope) returns an element that you should place in the DOM. The .html() part of your code is just inserting your uncompiled html, and you're not doing anything with the compiled element. Instead, you could do something like:

angular.element(el).empty().append($compile(html)(scope))

Upvotes: 1

Related Questions