Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
  }
}
like image 954
Silas Avatar asked Apr 04 '15 05:04

Silas


1 Answers

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

like image 106
sbedulin Avatar answered Sep 30 '22 18:09

sbedulin