AngularJS在加载应用程序后动态添加ng-include

时间:2015-04-04 05:48:57

标签: javascript jquery angularjs

我有一个带指令的更新按钮。单击该按钮时,目标元素应该接收一些包含ngInclude元素的新html。它似乎没有加载文件,它只是包含一个像<!-- ngInclude: nav.html -->这样的注释。如果我记录tpl变量,我会{ 0: <!-- ngInclude: nav.html -->, length: 1 }。这是我的指令和元素生成器代码。

指令

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

发电机

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

2 个答案:

答案 0 :(得分:6)

您需要编译插入生成内容的位置。

.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

答案 1 :(得分:0)

$compile(element)(scope)返回一个你应该放在DOM中的元素。代码的.html()部分只是插入未编译的html,而您对编译的元素没有做任何事情。相反,你可以做类似的事情:

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