2

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?

2
  • Why so You have The date in different objects. Combine your data into one json object. This saves You a lot of hassel. Commented Jan 22, 2015 at 16:59
  • @msohns I can't unfortunately that's why I'm struggling. Commented Jan 22, 2015 at 16:59

3 Answers 3

3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

It should be temperatures[$index] actually but that did it, thanks :) what exactly is the $index? Is that the current iteration value (1, 2, 3 etc) from cities loop?
3

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.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.