How to show object values in HTML persistently - javascript

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.

Related

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

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

AngularJS - how to show count 0 when ng-repeat and filter returns no rows

I am trying to print the count of elements filtered through a condition in AngularJS.
I am using ng-repeat to loop over collection and filter it to get counts and it works fine when there is value in it. However, when the filter returns empty result, Angular doesn't render the element and hence, I can't get it to display 0 count.
http://plnkr.co/edit/KNVwf2Yckxf1Qcyzcmea?p=preview
<div ng-repeat="i in iArr|filter:i.name='tim'">{{i.vals.length}}</div>
Does anyone have a clue to make it work in simple fashion.
Edit:
The question How to show a message when filter returns nothing in ng-repeat - AngularJS has a reply which actually solved my question but I don't know how. I am wondering if there is a very simple way to do it.
From that answer:
<select ng-model="shade" ng-options="shade for shade in shades"></select><br>
<ul>
<li ng-repeat="c in filteredColors = (colors | filter:shade)">{{c.name}}</li>
</ul>
<div ng-show="!filteredColors.length">No colors available</div>
The key is in c in filteredColors = (colors | filter:shade). The array result of the filter expression colors | filter:shade is being set to filteredColors, which then becomes available on the $scope object. Because of this, it can be used elsewhere in that controller scope. This is why it can be checked for its length to see if there are no colors.
Here is a working plnkr with solution and some extra
http://plnkr.co/edit/eOmHhR1VWjfYzHYqiEY1?p=preview
<body ng-controller="MainCtrl">
<label><input type="text" ng-model="search.vals">vals</label>
<label><input type="text" ng-model="search.name">name</label>
<div ng-repeat="i in filteredArr = (iArr | filter:search)">{{i.vals}} | {{i.name}}</div>
<div ng-if="!filteredArr.length">0</div>
</body>

AngularJs - Holding value of for loop string to use elsewhere

I've come a bit stuck in my angularjs project.
I run a for loop to query some nested JSON data and output it in 3 different variables inside an ng-repeat. So it makes up a title where i have the control over the elements that make up the title {{ number }} {{ shots }} {{ goals }}.
However, my knowledge of angularjs is stretched here because when I click on one of the events (from the ng-repeat list) it gives me a new tab, but I want to bring the title of that event to the new tab.
I can't call it as a scope variable as the last variable is still being held in there. I thought about assigning it as a new variable.. but was unsure how to actually do that in angularjs.
Here is the code i'm working with:
<li ng-repeat="event in events.events">
<div ng-if="actionType(event)" >
{{number}}
{{shots}}
{{goals}}
</div>
<a class="showPlayer" ng-click="showPlayer(event)">
View more stats
</a>
</li>
my angularjs is just a standard for loop which looks for values inside the js and assigns them as variables.
Any advice is very much appreciated.
EDIT: 24 hours later and I still can't crack this (very frustrating).
I'm not sure if there is a way to grab the string from the ng-click and clone that?
I don't want to have to run another check for the title when I already have the information, surely there is an 'angular' way to do this??
Please try this I am not sure but it might help you
<li ng-repeat="event in events.events">
<div ng-if="actionType(event)" >
{{event.number}}
{{event.shots}}
{{event.goals}}
</div>
<a class="showPlayer" ng-click="showPlayer(event.number,event.shots,event.goals)">
View more stats
</a>
</li>
Try using $rootScope.
Define a rootscope variable where event is handled and write your title in html like you did. {{title}}
$rootScope.title = "example";

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