【问题标题】:ng-repeat with ng-include not workingng-repeat 与 ng-include 不工作
【发布时间】:2014-01-22 16:16:43
【问题描述】:

我正在尝试使用包含ng-includeng-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 将按应有的方式呈现。我做错了什么?

【问题讨论】:

  • 你不能把 ng-repeat 放到模板中然后这样做?
  • 第一次迭代和其他迭代没有区别。项目数组的内容见。问题可能就在那里。
  • 我尝试将 ng-repeat 放在包含的模板中,但没有奏效。它只是向我展示了空模板。模板内的 ng-repeat 被忽略。

标签: angularjs angularjs-ng-repeat angularjs-ng-include


【解决方案1】:

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

解决您的问题的一个可能方法是不显示 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"
}
})

【讨论】:

  • 感谢您的解决方案。当我通过使用$location.path(route); 单击“链接”导航到页面时,它似乎有效。但是,一旦在页面上,如果我单击刷新,就会遇到原始问题,即未填写 ng-repeat 中的第一项(未填写第一项中的任何标签)。
  • @RomainFournereau 我不同意。 plnkr.co/edit/uBbXMlI5MYEcjIfXXeQT?p=preview
【解决方案2】:

我遇到了同样的问题,最后发现第一个元素没有在第一次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 在指令和服务中有一些很好的模板缓存示例:

Using $http and $templateCache from within a directive doesn't return results

【讨论】:

  • 我发现 $first 和 $last 在所有重复的范围内总是为我评估 true - 您认为您的问题与我的有关吗? $middle 和 $index 也工作正常 - 所以我正确使用范围变量 - 还有其他人吗?
【解决方案3】:

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

在你的情况下:

1) 定义一个指令:

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

2) 使用你的新指令:

<mytemplate />

...或者如果您是 concerned 关于 HTML 验证:

<div mytemplate></div>

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 2017-12-05
    • 2017-02-02
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2016-01-26
    • 2014-06-23
    相关资源
    最近更新 更多