Angular Json Looping - html

Hi I am new to angular I have a requirment as follows.
app.js
$scope.fields = {
"fields": {
"LastName1": "ABC",
"FirstName1": "XYZ",
"LastName2": "123",
"FirstName2": "345",
"LastName3": "PQR",
"FirstName3": "ASD",
}
};
In my html I need to loop over this and display in
index.html
<tr ng-repeat="key in fields">
this doesn't seem to work. Please help.
I want my output as
LastName1 ABC
FirstName1 XYZ
and so on.
Also If user makes any changes to this, I want to be able to push the changes back to fields Json. Please help.

You can use the (key, value) in object syntax.
In your case :
<div ng-repeat="(key1, value1) in fields">
<li ng-repeat="(key2, value2) in value1">{{key2}} : {{value2}}</li>
</div>.
But :
You need to be aware that the JavaScript specification does not define
the order of keys returned for an object. (To mitigate this in Angular
1.3 the ngRepeat directive used to sort the keys alphabetically.)
Version 1.4 removed the alphabetic sorting. We now rely on the order
returned by the browser when running for key in myObj. It seems that
browsers generally follow the strategy of providing keys in the order
in which they were defined, although there are exceptions when keys
are deleted and reinstated. See
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues
If this is not desired, the recommended workaround is to convert your
object into an array that is sorted into the order that you prefer
before providing it to ngRepeat. You could do this with a filter such
as toArrayFilter or implement a $watch on the object yourself.
More details : https://docs.angularjs.org/api/ng/directive/ngRepeat
Edit : What if you want to change the object now ?
You can't do :
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="value2" /><br />
{{key2}} : {{value2}}
</li>
</div>
Why ? Because ng-model will change value2 in the current scope, and not in your object fields as you don't use dot notation.
For each item/iteration, ng-repeat creates a new scope, which
prototypically inherits from the parent scope, but it also assigns the
item's value to a new property on the new child scope.
More details : https://github.com/angular/angular.js/wiki/Understanding-Scopes
But you can do :
<div ng-repeat="(key1, value1) in fields">
<h3>{{key1}}</h2>
<li ng-repeat="(key2, value2) in value1">
<input ng-model="fields[key1][key2]" /><br />
{{key2}} : {{value2}}
</li>
</div>
Take a look !!!

Try change to:
<tr ng-repeat="(key, value) in fields.fields">
<td>{{key}}</td>
<td>{{value}}</td>
</tr>
Here is a working plunker where you can update the model: http://jsfiddle.net/ttgfybk0/1/

Repeat data is in object format like
{
"LastName1": "ABC",
"FirstName1": "XYZ",
"LastName2": "123",
"FirstName2": "345",
"LastName3": "PQR",
"FirstName3": "ASD",
}
use the ng-repeat="(key, value) in expression"
<tr ng-repeat="(key, value) in fields.fields">
<td>{{key}} {{value}}</td>
</tr>
working example ishttp://plnkr.co/edit/Y5lPH1?p=preview

Related

Get JSON Multidimensional Array Keys - AngularJS

I am trying to build a form out of a JSON array. I need to load the keys into the HTML. Here is an example of this array:
{
"Fred": {
"description": "A dude"
},
"Tomas": {
"description": "Another Dude",
"Work": {
"Current": "No Employer",
"Previous": "Enron"
}
}
}
What I was are the values Fred & Thomas. When I run this in Angular HTML:
<div ng-repeat="set in sets">
<p ng-repeat="(key, val) in set">
<span ng-bind="key"></span>: <span ng-bind="val"></span>
</p>
</div>
I get the error "ngRepeat-dupes" although Fred and Tomas are not duplicate values. Any help is greatly appreciated.
You are getting the dupe error from a key being the same in both objects. You can fix it by using track by $index, however in the data you have provided, there are no dupes... see fiddle - https://jsfiddle.net/t4q4nrfp/36/
IF you did have dupes in your data though you just add in track by $index (you can use other things as well index is generally a default) like so :
<div ng-repeat="set in sets track by $index"> << add here if you have dupes are this level
<p ng-repeat="(key, val) in set track by $index"> << or here if dupes at this level
<span ng-bind="key"></span>: {{val}} <span ng-bind="val"></span>
</p>
</div>
Also, just to be clear, you are working with an object not an array.
use track by $index:
<div ng-repeat="set in sets track by $index">
<p ng-repeat="(key, val) in set track by $index">
<span ng-bind="key"></span>: <span ng-bind="val"></span>
</p>
</div>

ng repeat does not return variable from JSON file

I have the following html code that belongs to a template in AngularJS framework:
<ul class="sb-parentlist">
<h1 class={{headerClass}}> Popular</h1><div data-ng-repeat="data in data track by $index">
<li>
<span class="sb-text-title" href="#" ng-click="openFaq = ! openFaq"><b>{{data[$index].faq.frage |translate}}</b></span>
<span ng-show="openFaq" class="sb-text">
<br>
{{data[$index].faq.antwort |translate}}
</span>
</li>
</div>
</ul>
I am getting the number of "li" elements on my browser correctly on printing the results, but the variables are not defined as they should be, blank entries appearing.
here is the JSON entry:
{
"faq":
{"frage":"HB_START_FAQ_Q",
"antwort":"HB_START_FAQ_A"}
,
"screencast":"HB_START_SCREENCAST"
},
{
"faq":
{"frage":"HB_START_FAQ_Q_1",
"antwort":"HB_START_FAQ_A_1"}
,
"screencast":"HB_START_SCREENCAST_1"
},
{
"faq":
{"frage":"HB_START_FAQ_Q_2",
"antwort":"HB_START_FAQ_A_2"}
,
"screencast":"HB_START_SCREENCAST_2"
},
{
"faq":
{"frage":"HB_START_FAQ_Q_3",
"antwort":"HB_START_FAQ_A_3"}
,
"screencast":"HB_START_SCREENCAST_3"
}
I am interested to get the nested item. Any ideas?
Because data is ambiguous between the collection name and the item being iterated over - change your ngRepeat syntax:
data-ng-repeat="item in data track by $index"
And use item[$index]. Im not entirely sure why you aren't just doing data.faq - you need to select by the $index

access certain element of JSON in angular JS

Below is my JSON file:
[
{
"Name":"Peter England Shirt",
"Prodimage":["./images/zoom/zoom1hi.jpg","./images/zoom/zoom2hi.jpg","./images/zoom/zoom3hi.jpg"],
"actualPrice":"90",
"discountedPrice":"70",
"desc":"Cotton",
"Prodcolor":["#f1f40e","#adadad","#4EC67F"],
"quantity":[1,3,4,5,60],
"size":["XL","L","M","S"],
"detail":"Take it away",
"sizeChart":["16 waist","Measurements taken from size 30","Model wears size 31. Model is 6'2"],
"shipping":[
{
"type":"Standard",
"days":"5-6 days",
"cost":"200"
},{
"type":"Next day",
"days":"1 days",
"cost":"500"
}
],
"sellerList":[
{
"sellerName":"ABC",
"price":"566",
"deliveryDay":"4-5 working days"
},{
"sellerName":"SEDF",
"price":"300",
"deliveryDay":"4-5 working days"
},{
"sellerName":"QWER",
"price":"555",
"deliveryDay":"2-5 working days"
}
]
}
]
The JS file is as below:
var pJson="./json/product.json";
$http.get(pJson).success(function(response){
$scope.product=response;});
Now, if I want to access "Name" attribute I can call {{product[0].Name}}.
But I am not able to access Prodimage attribute using ng-repeat. I am trying like this:
<div ng-repeat="image in product.Prodimage">
{{image[0]}}
</div>
is this wrong?>
Yes this is wrong ,, note that you have the product object as array ,, so if you want the first object you should do this
<div ng-repeat="image in product[0].Prodimage">
{{image[0]}}
</div>
or if you want to iterate over all the products ,, you need to make a nested ng-repeat
<div ng-repeat="p in product">
<div ng-repeat="image in p.Prodimage">
{{image[0]}}
</div>
</div>
You could loop over it, becasue the outside is technically an array, and use $first for you example of wanting to only grab the first image. You could also use $index but running it through a function that checks the $index.
Fiddle here http://jsfiddle.net/HB7LU/15324/
I just re worked it to loop twice like so
<div ng-repeat="prod in product">
<div ng-repeat="image in prod.Prodimage">
<div ng-show="$first">
{{image}}
</div>
</div>
</div>
then put a div inside the inner repeat that will only show if it's the first item. Again you could change that logic to show by index, or whatever you want. So if you know the index you could change that same logic to this -
see fiddle - http://jsfiddle.net/HB7LU/15332/
<div ng-show="checkIndex($index)"> << or whatever index you want
{{image}}
</div>
and in the controller
$scope.checkIndex = function(item){
if(item === 0){
return true;
}else{
return false;
}
}
You just pass the index of the current item in the repeat and check it. I would recommend this logic over the Prodimage[0] logic so you are not hardcoding it into the html, so if you have to change the desired index, you change it in the controller, not template. The checkIndex is a quick example, you could change that to do whatever you want.
$scope.product[n].Prodimage is an array. So, you need to loop through your product array first, and then loop through the Prodimage array of each product:
<div ng-repeat="prod in product">
<div ng-repeat="image in prod.Prodimage">
{{ image }}
</div>
</div>
Of course, you could also just access the nth image using something like:
<div ng-repeat="prod in product">
{{ prod.Prodimage[0] }}
</div>
Can you change your json to
"Prodimage":[
{ "loc": "./images/zoom/zoom1hi.jpg"},
{ "loc": "./images/zoom/zoom2hi.jpg"},
{ "loc": "./images/zoom/zoom3hi.jpg"}],
then your loop should work
<div ng-repeat="image in product.Prodimage">
{{image.loc}}
</div>

Show json with AngularJS

Im new to AngularJS. Now I have a json object from my spring controller, how do i use/print in my jsp?
I tried something like this. the console shows the json perfectely, and with angular it does not...
<div data-ng-init="stats=${stats}">
<li data-ng-repeat="stat in stats">{{stat.name}}</li>
</div>
<script>
console.log(${stats});
</script>
Json:
{ "Types": [{"name": "study", "value":0},{"name": "health", "value":0},{"name": "culture", "value":0},{"name": "nightlife", "value":0},{"name": "other", "value":0},{"name": "friendship", "value":0}] })
Because JSON string must be properly quoted if placed into HTML attribure value, you either escape " characters in JSON or probably better use ' quotes for ngInit:
<div data-ng-init='stats=${stats}'>
<li data-ng-repeat="stat in stats.Types">{{stat.name}}</li>
</div>
Demo: http://plnkr.co/edit/XLIE9VCSn9gL3oO6ULol?p=info
You need to reference the array property of stats.
<li data-ng-repeat="stat in stats.Types">{{stat.name}}</li>

AngularJS: How to get the key of a JSON Object

I am unsure if this has got anything to do with AngularJS at all and if it is only JSON related.
Anyhow, let us say that we have the following JSON:
$scope.dataSets = {
"names": ["Horace", "Slughorn", "Severus", "Snape"],
"genders": ["Male", "Female"]
}
Now, I am using the ng-repeat directive to print the above as follows:
<div ng-repeat="data in dataSets>
//Continue readig to know what I am expcting here
</div>
What I expect within the <div></div> tags is to print "name" and "genders". That is, I wish to print the keys of the JSON. I have no idea what the keys are, as in they could be anything. How can I do this?
As docs state it:
(key, value) in expression – where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
<div ng-repeat="(key, data) in dataSets">
{{key}}
</div>
for accessing Json key-value pair from inside controller in AngularJs.
for(var keyName in $scope.dataSets){
var key=keyName ;
var value= $scope.dataSets[keyName ];
alert(key)
alert(JSON.stringify(value));
}
if dataSets is an array and not an object you first need to ng-repeat the array items and then the key or value.
<div ng-repeat="item in dataSets">
<div ng-repeat="(key, value) in item">
{{key}}
{{value}}
</div>
</div>
just my 2 cents.
For every dataSet in dataSets, print the key and then iterate through the individual items:
<div ng-repeat="(key, dataSet) in dataSets">
<div>{{key}}</div>
<div ng-repeat="value in dataSet">
{{value}}
</div>
</div>
{{dataset}} can be displayed in one go also, the array would be displayed as a comma separated list of values.