简体   繁体   English

带routeParams和嵌套数组的角度ng-repeat

[英]Angular ng-repeat with routeParams and nested array

I am using Angular JS and I am having an issue using the ng-repeat directive in combination with routeParams and a nested array within my JSON data. 我正在使用Angular JS,并且在将ng-repeat指令与routeParams和JSON数据中的嵌套数组结合使用时遇到问题。

I have this data (work.json is the file name): 我有此数据(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"]
},
]

I have this controller: 我有这个控制器:

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;
});
}]);

Then this view.: 然后这个视图。:

<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>

The items in the first div work fine. 第一格中的项目工作正常。 The items in the second div with ng-repeat, not surprisingly, do not show up. 毫不奇怪,第二格中具有ng-repeat的项不会显示。 What I have here currently is a guess as to how to implement the loop. 我目前在这里只是对如何实现循环的猜测。

When using routeParms how do I iterate through a nested array within my data using ng-repeat? 使用routeParms时,如何使用ng-repeat遍历数据中的嵌套数组? Is ng-repeat what I should be using here? 我应该在这里使用ng-repeat吗?

Joao Leal is right, according to sample JSON data, workImages is array of strings. Joao Leal是正确的,根据示例JSON数据,workImages是字符串数组。

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

Should work. 应该管用。

For sake of simplification you may set $scope.detail like: 为了简化起见,您可以将$scope.detail设置$scope.detail

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

so you can omit [whichItem] in every detail data binding in view. 因此,您可以在视图的每个详细数据绑定中省略[whichItem]

And you should not set ng-model for div. 并且您不应该为div设置ng-model。 It is intended for two-way bound form inputs. 它用于双向绑定表单输入。 It will just work without that. 没有它,它将正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM