9

我正在尝试使用ng-repeat包含ng-include. 问题是 ng-repeat 中的第一个元素只是ng-include模板,没有ng-repeat填充任何数据。有没有办法我可以以某种方式将模板绑定到第一个元素ng-includeng-repeat

<div ng-repeat="item in items">
    <div ng-include src="'views/template.html'"></div>
</div>

例如,如果 myng-repeat包含 10 个项目,则呈现的第一个项目将只是空模板。项目 2-10 将按应有的方式呈现。我究竟做错了什么?

4

3 回答 3

26

首先确保项目的第一个索引中包含的数据实际上具有您想要的数据。

解决您的问题的一种可能方法是不显示 ng-repeat 的第一个索引:

<div ng-repeat="item in items" ng-show="!$first">
   <div ng-include src="'views/template.html'"></div>
</div>

这实际上可能无法解决您的问题的根源,但它仍然可以让您的应用程序更像您所期望的那样工作。


另一种可能的解决方案:

<div ng-repeat="item in items" ng-include="'views/template.html'"></div>

看这里的例子:

http://plnkr.co/edit/Yvd73HiFS8dXvpvpEeFu?p=preview


另一种可能的解决方法只是为了更好地衡量:

使用一个组件:

html:

<div ng-repeat="item in items">
   <my-include></my-include>
</div>

js:

angular.module("app").directive("myInclude", function() {
return {
    restrict: "E",
    templateUrl: "/views/template.html"
}
})
于 2014-01-05T06:26:01.147 回答
1

我遇到了同样的问题,最后发现第一个元素没有在第一次ng-repeat迭代时被及时提取和编译。使用$templateCache将解决问题。


您可以将模板缓存在脚本标记中:

<script type="text/ng-template" id="templateId.html">
    <p>This is the content of the template</p>
</script>


或者在您的应用程序的运行功能中:

angular.module("app").run(function($http, $templateCache) {
    $http.get("/views/template.html", { cache: $templateCache });
});


您也可以$templateCache在指令中使用,尽管设置起来有点困难。如果您的模板是动态的,我建议您创建一个模板缓存服务。这个 SO question 在指令和服务中有一些很好的模板缓存示例:

在指令中使用 $http 和 $templateCache 不会返回结果

于 2014-07-23T07:04:40.103 回答
1

使用对我有用的指令:https ://stackoverflow.com/a/24673257/188926

在你的情况下:

1)定义一个指令:

angular.module('myApp')
  .directive('mytemplate', function() {
    return {
      templateUrl: 'views/template.html'
    };
  });

2)使用你的新指令:

<mytemplate />

...或者如果您担心HTML 验证:

<div mytemplate></div>
于 2014-08-11T10:07:41.770 回答