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

6

我有一个带指令的更新按钮。当点击按钮时,目标元素应该接收一些新的HTML内容,其中包括ngInclude元素。但是它似乎没有加载文件,而只是包含如下的注释: <!-- 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;
  }
}

你需要在点击事件中执行 $scope.$apply() 来运行脏检查循环。 - Pankaj Parkar
1
@pankajparkar,感谢您的回复。我已经更新了我的答案。我发现需要在将$compile添加到元素后再进行编译。我还添加了scope.$apply()。现在它可以加载文件,但仍然无法将这些文件的内容应用到ng-include中。 - Silas
2个回答

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


我的问题是我在解决方案中忘记调用scope.$apply()。谢谢。 - Marek Pavelek

1

$compile(element)(scope) 返回一个元素,你应该将其放置在 DOM 中。你代码中的 .html() 部分只是插入未编译的 html,而且你没有对编译后的元素做任何操作。相反,你可以做如下操作:

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

我无法通过这种方式使其工作。编译元素而不是HTML可以解决问题。 - Silas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接