使用ng-repeat添加html,其中html也包含ng-repeat

时间:2015-11-18 17:21:44

标签: javascript html angularjs

我的代码使用ng-repeat将html代码绑定到div,如此

<div ng-repeat="item in items" ng-bind-html="item.html">    

在传入的html代码中,我想添加一个带有ng-repeat指令的表,以便在从单独的Web服务返回时可以使用数据填充它。 items.item中的html看起来像:

<table>
  <tr ng-repeat=\"person in people\">
    <td>{{person.id}}</td>
    <td>{{person.firstName}}</td>
    <td>{{person.lastName}}</td>
  </tr>
</table>

目前我的输出看起来像

{{person.id}}   {{person.firstName}}    {{person.lastName}}

有什么建议可以让它发挥作用吗?

2 个答案:

答案 0 :(得分:2)

ng-bind-html不会为您编译内容。

您可以使用此指令,该指令基于ng-bind-html的源代码,但已修改为也可编译:

app.directive('compileHtml', ['$sce', '$parse', '$compile',
  function($sce, $parse, $compile) {
    return {
      restrict: 'A',
      compile: function ngBindHtmlCompile(tElement, tAttrs) {
        var ngBindHtmlGetter = $parse(tAttrs.compileHtml);
        var ngBindHtmlWatch = $parse(tAttrs.compileHtml, function getStringValue(value) {
          return (value || '').toString();
        });
        $compile.$$addBindingClass(tElement);

        return function ngBindHtmlLink(scope, element, attr) {
          $compile.$$addBindingInfo(element, attr.compileHtml);

          scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {

            element.html($sce.trustAsHtml(ngBindHtmlGetter(scope)) || '');
            $compile(element.contents())(scope);
          });
        };
      }
    };
  }
]);

用法:

<div ng-repeat="item in items" compile-html="item.html">   

答案 1 :(得分:1)

您必须先使用$compile服务编译您的html。你可以查看文档。

https://docs.angularjs.org/api/ng/service/ $ compile