Using ng-repeat on multiple arrays - javascript

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?

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>

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.

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/

Related

How to use the ng-repeat $index variable in an AngularJs expression?

I'm generating a lot of HTML with ng-repeat. I rely on the $index variable in order to index data in my controller.
I do alot of stuff like
ng-submit="validateExistingGuest($index)"
In this case, an undetermined number of HTML forms is generated, hence the index.
Problem is, i sometimes need to use this variable inside a different kind of expression. That would look something like that:
ng-if= "user{{$index}}.valid"
Of course, that doesn't work. I tried ways of constructing that expression, with no success.
How would one go about doing this?
You need something like
ng-if="user[$index].valid
<div ng-repeat="value in user track by $index"> ...
//now you can use the {{$index}}
<div ng-if="user[$index].valid">Show only if valid!</div>
</div>
Why don't you use the object instead the $index?, try
<div ng-repeat="car in cars" >
<p {{car}}></p>
<button ng-click="buy(car)" > buy </button>
</div>

Angular 1.x ng-repeat shows data while straight template binding doesn't display

This ng-repeat shows me data but not {{ ...}}
ng-repeat WORKS
<div ng-repeat="x in confirm.booking.flightData">
{{x.DestinationAirport}}
</div>
Template Binding DOES NOT WORK
{{confirm.booking.flightData.DestinationAirport}}
is this because of the Arrays of data?
console.log shows this
confirm.booking > Object { flightData: Array[2], travelers: Array[1]
What I'm after is also going to be data in flightData Array Object 0
Picture below
example I was wanted to display data inside the Segments per the picture, Segments is an Array[2]
{{confirm.booking.flightData[1].Segments[0].FlightNumber}}
I don't believe the above will work, but based on the picture of my javascript object , what do I need to do?
It is obvious that {{confirm.booking.flightData.DestinationAirport}} will not work as flightData is an array.
Did you check out {{confirm.booking.flightData[1].Segments[0].FlightNumber}} - becasue it will work. See a demo below:
angular.module("app", []).controller("ctrl", function($scope) {
$scope.array = [{key:[1, {key: 'value2'},3]}, {key: 'value1'}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="wrapper" ng-app="app" ng-controller="ctrl">
<div>{{array[0].key[1].key}}</div>
</div>
If your ng-repeat loop is displaying data and the binding {{ }} is NOT, then yes you are simply not looking at the array.
Based on YOUR data, you seem to already have the answer! You are not showing US all your segment data, but if there is a FlighNumber then
{{confirm.booking.flightData[1].Segments[0].FlightNumber}}
SHOULD WORK !
You better be thinking about best practices as that is going to not be so awesome to maintain...
cheers

How to show object values in HTML persistently

Let's suppose I am having an object like y={1,2,3}. I want to display its value using Angular in HTML.
So what I did is:
for(var i=0;i<y.length;i++){
$scope.data=y[i]; //transferring
}
and in my HTML it is written:
<html>
{{data}}
</html>
Now I know that it is showing the last value(3) because the data value is updated at the end, and since the last value of the loop is 3 it sets the 3 in HTML. So my question is how can we fix this problem?
First problem is that y should be an array:
var y = [1, 2, 3]
Second, you should use ng-repeat in your html, not for loop:
<span ng-repeat="num in y">
{{ num }}
</span>
Most importantly, you should look through the documentation and some tutorials first. Because it is the most basic part of angularjs which is taught first in every book or tutorial.
UPDATE
If you want to show object properties in your html, you can do this:
<span ng-repeat="(key, value) in y">
{{key}} - {{ value }}
</span>
Yea I got the answer!
Store every response in an array and then render that array using ng-repeat.
It was so easy that it dint scratched my mind.

How to filter with angularJS value from JSON

Hi guys i need a quick response, sorry for my lack of english but here is the problem:
I'm doing ng-repeat on a JSON object i recieve from the API. The object has listin it etc. and the Json object has PLACE value. Place is a int that gives me the position where to put the object, and how to put it in a LIST!
so i do the ng-repeat="s in object" and now i need the s.PLACE value to Filter the objects. How do i do that?
<div class="some class" ng-repeat="s in Object| limitTo:6:0 ">
<li>{{s.Name}}</li>
</div>
example, just how mI supposed to tell him, IF PLACE IS == 1 SKIP don ng-Repeat item, or when PLACE==2 put it in the last place. Is this possible with ng-repeat?
<div class="some class" ng-repeat="s in Object| limitTo:6:0 ">
<li ng-if="s.PLACE > 1">{{s.Name}}</li>
</div>
So i found out i can use ng-if for stuff like this!

Select different child JSON element with select input in AngularJS

I am printing a list of food types by making an API call per category. The food in the categories have this JSON structure:
{"uid":"56",
"title":"Nussbrot",
"code":"X 39 2000000",
"final_factor":"0",
"sorting":"0",
"unit":[
{"title":"Scheiben",
"gram":"45",
"max":"100"
},
{"title":"Messerspitzen",
"gram":"250",
"max":"12"}
]
}
I am looping through & printing the values out into a template. No problem. I am printing the "unit" values into a select box:
<option ng-repeat="title in food.unit">{{ title.title }}</option>
And I am currently printing out the grams & title of the first unit in each food like this:
<div class="max">Max is: {{ food.unit[0].max }}</div>
<div class="grams">Grams is: {{ food.unit[0].gram }} </div>
How can I make this dynamic, so that I am printing out the max & grams of the currently selected unit?
Here's my Plunkr.
Angular makes dealing with options and selected options very easy. You should stop thinking in terms of indexes or value. With angular you can bind the entire object, so there's no need to look it up. For example you could do the following for your select:
<select ng-model='selectedUnit' ng-options="unit as unit.title for unit in food.unit"></select>
Let me briefly explain the expression for ng-options
unit in food.unit means we will iterate over the food.unit array storing each value in unit as we go along.
unit as unit.title means what we are putting in the ng-model whenever the user selects an item is the entire unit object itself. The as unit.title tells angular to use the title of the unit as a display for the option.
What this ends up doing is that whenever the user selects one of the options, the entire unit object will be stored in the ng-model variable (in this case selectedUnit). This makes it really easy to bind it elsewhere. For example you can just do:
<div class="unit">Unit is: {{ selectedUnit.title }}</div>
<div class="max">Max is: {{ selectedUnit.max }}</div>
<div class="grams">Grams is: {{ selectedUnit.gram }} </div>
In angular, if you find yourself dealing with indexes or ids and then looking things up by id or index then you are typically doing it wrong. One of the biggest advantages of using angular is how easy it is to deal with objects, and you should really take advantage of it.
For example, I often see newbies doing something like
<li ng-repeat="person in persons">{{person.name} <a ng-click="savePerson(person.id)">Save</a></li>
And then in their code they use the id to look up the person from an array:
$scope.savePerson = function(id){
var person = persons[id];
$http.post('/persons/'+id, person);
};
This kind of lookup is almost always unecessary with angular. You can almost alway just pass the person right away:
<li ng-repeat="person in persons">{{person.name} <a ng-click="savePerson(person)">Save</a></li>
And then have the click handler take the person:
$scope.savePerson = function(person){
$http.post('/persons/'+person.id, person);
};
I know I strayed a bit from your original question. But hopefully this makes sense and helps you write things more simply using the "angular way"
Her is the plunkr for your example:
http://plnkr.co/edit/lEaLPBZNn0ombUe3GPa9?p=preview
you can fist of all handle the selected item with the ng-selected:
http://docs.angularjs.org/api/ng.directive:ngSelected
<select>
<option ng-repeat="title in food.unit" ng-selected="selectedIndex=$index">{{ title.title }}</option>
</select>
<div class="max">Max is: {{ food.unit[selectedIndex].max }}</div>
<div class="grams">Grams is: {{ food.unit[selectedIndex].gram }} </div>
This should propably work ;) Havn't tryed it yet!

Categories