【问题标题】:Angular ng-repeat with routeParams and nested array带有 routeParams 和嵌套数组的 Angular ng-repeat
【发布时间】:2014-11-06 12:58:05
【问题描述】:

我正在使用 Angular JS,我在将 ng-repeat 指令与 routeParams 和 JSON 数据中的嵌套数组结合使用时遇到问题。

我有这个数据(work.json 是文件名):

[
{
“workName”:”Sample”,
"workLocation”:”Sample Location”,
"workDescription"Sample Description",
"workImages": ["1.png","2.png","3.png"]
},
{
“workName”:”Sample”,
"workLocation”:”Sample Location”,
"workDescription"Sample Description",
"workImages": ["4.png","5.png","6.png"]
},
]

我有这个控制器:

workControllers.controller('DetailController', ['$scope', '$http', '$routeParams', 
function ($scope, $http, $routeParams) {
$http.get('data/work.json').success(function(data) {
$scope.detail = data;
$scope.whichItem = $routeParams.itemId;
});
}]);

然后这个视图。:

<div ng-model="detail">
<h1>{{detail[whichItem].workName}}</h1>
<p>{{detail[whichItem].workDescription}}</p>
</div>

<div ng-repeat="item in detail[whichItem].workImages">
<img ng-src="{{item.id}}" />
</div>

第一个 div 中的项目工作正常。毫不奇怪,第二个 div 中带有 ng-repeat 的项目不会出现。我目前在这里的猜测是关于如何实现循环。

使用 routeParms 时,如何使用 ng-repeat 遍历数据中的嵌套数组?我应该在这里使用 ng-repeat 吗?

【问题讨论】:

  • item.id 解析为什么?不应该只是物品吗?

标签: javascript json angularjs ng-repeat


【解决方案1】:

Joao Leal 是对的,根据示例 JSON 数据,workImages 是字符串数组。

<div ng-repeat="item in detail[whichItem].workImages">
    <img ng-src="{{item}}" />
</div>

应该可以。

为简化起见,您可以将$scope.detail 设置为:

$http.get('data/work.json').success(function(data) {
    $scope.detail = data[$routeParams.itemId];
});

因此您可以在视图中的每个详细数据绑定中省略 [whichItem]

而且你不应该为 div 设置 ng-model。它适用于双向绑定表单输入。没有它就可以工作。

【讨论】:

  • 太好了,谢谢。这些调整奏效了。我对视图中的 ng-repeat 进行了细微更改,不确定它是否是正确的语法,但它有效:ng-repeat="item in detail.workImages track by $index"
  • 按 $index 跟踪,以便数组中的每个项目都是唯一的
猜你喜欢
  • 2015-06-01
  • 1970-01-01
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多