Using ng-repeat on multiple arrays

你说的曾经没有我的故事 提交于 2020-01-04 14:15:27

问题


I'm making a weather application but I'm stuck on what should be a simple task but I can't wrap my head around how this works since I'm new to Angular. Basically what I need is to iterate over two arrays at once and set some values from this array.

In theory this is what I wanna accomplish:

<div ng-repeat="city in cities" ng-repeat="temp in temperatures" id={{city.id}}>
    <span>{{temp}}</span>
</div>

But obviously you can't put multiple repeaters like this. If I put an ng-repeat on the span I get 12 spans but I only need 1 and I need this 1 to contain the current value of the iteration in the temperatures.

The arrays looks like this after being created dynamically using an API:

Cities: [object, object, object, object, object, object, object, object, object, object, object, object]

Temperatures: [-2.3, -0.2, -1.2, -25.4, 2.9, -4.8, -2.2, -12.1, 0.3, -5.9, -7.7, -0.1]

How would I do this?


回答1:


Use an index (assuming temperatures is the array of temperatures defined in the same controller):

<div ng-repeat="city in cities">
    <span>City: {{city}} - Temperature: {{temperatures[$index]}}</span>
</div>



回答2:


you cant use two ng-repeat in one div.

you need a alternative way of doing this, please try this suggestion

<div ng-repeat="city in cities" id={{city.id}}>
    <span>{{temperatures[$index]}}</span>
</div>

---- for the best practice

don't use $index its a bad practice but you can achieve what u want in this case.

you can do something like this,

<div ng-repeat="city in cities">
    <span>City: {{city}} - Temperature: {{ getTemprature(city) }}</span>
</div>

in controller,

$scope.getTemprature = function(city) {
    var index = cities.indexOf(city);
    return temperatures[index];
}

because if you use orderBy with the ng-repeat $index will not behave like u assume, $index will get the ordered array $index not the actual array $index.




回答3:


You can accomplish this with lodash's zip function. Try this:

Controller

$scope.combinedData = _.zip(cities, temperatures);

View

<div ng-repeat="row in combinedData" id="{{row[0].id}}">
    <span><b>{{row[0].name}}</b> {{row[1]}}</span>
</div>

Working fiddle: http://jsfiddle.net/hojrhLx5/1/



来源:https://stackoverflow.com/questions/28094394/using-ng-repeat-on-multiple-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!