Chrillewoodz
Chrillewoodz

Reputation: 28328

Using ng-repeat on multiple arrays

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?

Upvotes: 2

Views: 5140

Answers (3)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

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.

Upvotes: 3

Nate Barbettini
Nate Barbettini

Reputation: 53600

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/

Upvotes: 1

ltalhouarne
ltalhouarne

Reputation: 4636

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>

Upvotes: 3

Related Questions