我正在尝试使用包含ng-include的ng-repeat。问题是ng-repeat中的第一个元素只是ng-include模板,没有填充来自ng-repeat的任何数据。有没有办法从ng-include绑定模板,这样它就可以在第一个ng-repeat上工作
<div ng-repeat="item in items">
<div ng-include src="'views/template.html'"></div>
</div>例如,如果我的ng-repeat包含10个项目,那么呈现的第一个项目将只是空模板。项目2-10将按其应有的方式呈现。我做错了什么?
发布于 2014-01-05 14:26:01
首先,确保项目的第一个索引中包含的数据实际具有所需的数据。
您的问题的一个可能的解决方案是简单地不显示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-07-23 15:04:40
我遇到了同样的问题,最终发现第一个元素没有被及时获取和编译,无法进行第一次ng-repeat迭代。使用$templateCache可以解决这个问题。
您可以在script标记中缓存模板:
<script type="text/ng-template" id="templateId.html">
<p>This is the content of the template</p>
</script>
或者在你的应用程序的run函数中:
angular.module("app").run(function($http, $templateCache) {
$http.get("/views/template.html", { cache: $templateCache });
});
您也可以在指令中使用$templateCache,尽管设置起来有点困难。如果您的模板是动态的,我建议您创建一个模板缓存服务。这个SO问题有一些在指令和服务中缓存模板的很好的例子:
Using $http and $templateCache from within a directive doesn't return results
发布于 2014-08-11 18:07:42
使用一个对我有效的指令:https://stackoverflow.com/a/24673257/188926
在您的案例中:
1)定义指令:
angular.module('myApp')
.directive('mytemplate', function() {
return {
templateUrl: 'views/template.html'
};
});2)使用新指令:
<mytemplate />..。或者,如果您对超文本标记语言验证感兴趣,请使用concerned:
<div mytemplate></div>https://stackoverflow.com/questions/20929999
复制相似问题