I need to access the values of "city" and "nation" inside the array the following json file using AngularJS with ng-repeat.
This is my Json file:
[
{
"name": "first",
"location": [
{
"city" : "milan",
"nation" : "italy"
}
],
"visibility": 1
},
{
"name": "second",
"location": [
{
"city" : "new york",
"nation" : "usa"
},
{
"city" : "london",
"nation" : "uk"
}
],
"visibility": 1
}
]
My problem is that I need to get City and Nation as text string values, because I need to add them as css class name inside a tag, basically like this:
<div class="milan italy"></div>
<div class="new york usa london uk></div>
I'm not able to figure it out how to do this.
I tried with this code but nothing is shown:
<div ng-repeat-start="tile in tiles"></div>
<div class="mix {{ tile.location.city }} {{ tile.location.nation }}"></div>
<div ng-repeat-end></div>
Thank you in advance for your suggestions.
As #MattDionis said, you would need to specify ng-class, not just class. What you can try is using a function for ng-class. So you can do
<div ng-repeat="tile in tiles">
<div ng-class="getLocation(tile)"></div>
</div>
$scope.getLocation = function(tile) {
var resp = '';
for (var i = tile.location.length; i-- > 0;) {
resp = resp + tile.location[i].city + ' ' + tile.location[i].nation;
}
return resp;
}
I'm sure there's a better way to combine them than that, but that's what I came up with off-hand
First, you want to use ng-class rather than simply class to properly evaluate those bindings.
Also, tile.location appears to be an array of objects rather than simply an object. Therefore, {{ tile.location.city }} would not work, but {{ tile.location[0].city }} should.
The remaining issue would be how to loop through mutliple city/nation values within ng-class. I'll get back to you on that.
Please see demo below
You can create function to transform your array of object to string ie:
$scope.tostring = function (array) {
var res = "";
angular.forEach(array, function (obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " +obj[k];
}
}
});
return res;
};
var app = angular.module('app', []);
angular.module('app').controller('homeCtrl', homeCtrl);
homeCtrl.inject = ['$scope'];
function homeCtrl($scope) {
$scope.titles = [{
"name": "first",
"location": [{
"city": "milan",
"nation": "italy"
}],
"visibility": 1
}, {
"name": "second",
"location": [{
"city": "new york",
"nation": "usa"
}, {
"city": "london",
"nation": "uk"
}
],
"visibility": 1
}];
$scope.tostring = function(array) {
var res = "";
angular.forEach(array, function(obj) {
console.log(obj);
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
res += " " + obj[k];
}
}
});
return res;
};
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="homeCtrl">
<div ng-repeat="title in titles">
<h3 ng-class="tostring(title.location)">{{title.name}} My class is:*{{tostring(title.location)}}* </h3>
</div>
</body>
</html>
Related
I have a code as a shown below in which I am not sure how to do referencing.
<p id="demo" ></p>
<p id="options"></p>
<script>
var myObj, myJSON, text, obj;
myObj = {
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
}
}
}
}
//Storing data:
// converting JS object into String
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
//Retrieving data:
text = localStorage.getItem("testJSON");
//converting String into JS object
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = // code
Problem Statement:
I am wondering what changes should I make in the below line(which is the last line in the above code) so that the output should be Huston Rocket.
document.getElementById("demo").innerHTML = // code
I tried in the following way but somehow I am not able to reach Huston Rocket
document.getElementById("demo").innerHTML = myObj.quiz.sport.q1.answer;
You are using incorrect name, after Json parsing, your Json object is 'obj'
So use it as
document.getElementById("demo").innerHTML = obj.quiz.sport.q1.answer;
I have one JSON data how to display these data using ng-repeat?
I am new in angularJS. I dont how to to repeat nested in ng-repeat in angularJS
This is my JSON data.Please help me to show the outputs?
How to get these data using ng-repeat
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
etc....
See $scope.orders is an array
I call an api and got this data
orderPromise.success(function(data, status, headers, config)
{
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
});
I need to display this output using ng-repeat in html page
customerId=56b6f841d085980f2241909c
name: Maxxwell
Total Product=2
Total Price=685 //(2*18.5)+240(3*(240*10/100))
createdOn: 07-Feb-2016 10:50:05 UTC
:
:
I don't know its correct or not but its not working in my html page
Please correct me if it is wrong?
$scope.ordertemp=[];
$scope.orderval={};
var countval = $scope.orders.length;
for(var j=0;j<countval;j++)
{
$scope.orderval.buyerId = $scope.orders[j].customerId;
$scope.orderval.name = $scope.orders[j].address.name
$scope.orderval.totalitem = $scope.orders[j].products.length
var count = $scope.orders[j].products.length
var total = 0;
var save=0;
for(var i=0;i<count;i++)
{
var actualprice = 0;
var offer = 0;
var price = 0;
var quantity=0;
actualprice = $scope.orders[j].products[i].productDetails.actualPrice;
offer = $scope.orders[j].products[i].productDetails.offer;
quantity = $scope.orders[0].products[i].quantity;
price = actualprice - (actualprice * offer)/100
total = total + (price * quantity);
save = save +((actualprice/100)*offer)* quantity
}
}
$scope.orderval.totalprice = total;
$scope.orderval.save = save;
$scope.ordertemp.push($scope.orderval);
alert(JSON.stringify($scope.ordertemp));
When i alert this data will shown but its not repeated in my ui page Why?
Can i add any filter for using this to add Total price?
you can also do like this,First flatten your response as your need. Like below
$scope.orders=
[
{
"customerId": "56b6f841d085980f2241909c",
"address": {
"name": "Maxxwell",
"city": "Texas",
"country": "USA",
},
"products": [
{
"productId": "569df8bcd08598371e9b5ad9",
"quantity": 2,
"productDetails": {
"itemId": "569df86dd08598371e9b5ad8",
"actualPrice": "18.5",
"offer": 0,
"modifiedOn": "19-Jan-2016 12:35:32 UTC"
}
},
{
"productId": "569f2d2dd085980ecfc8997b",
"quantity": 3,
"productDetails": {
"itemId": "569f294dd085980ecfc89971",
"actualPrice": "240",
"offer": 10,
"modifiedOn": "06-Feb-2016 09:09:46 UTC"
}
}
],
"createdOn": "07-Feb-2016 10:50:05 UTC"
}
]
Now code for flatten the response
var myFinalArr = [];
for (index in $scope.orders) {
var obj = {};
var productSum = 0;
obj.customerId = $scope.orders[index].customerId;
obj.name = $scope.orders[index].address.name;
obj.city = $scope.orders[index].address.city;
obj.country = $scope.orders[index].address.country;
obj.createdOn = $scope.orders[index].createdOn;
obj.productCount = $scope.orders[index].products.length;
for (index2 in $scope.orders[index].products) {
productSum = parseFloat(productSum) + parseFloat($scope.orders[index].products[index2].productDetails.actualPrice);
if (index2 == ($scope.orders[index].products.length) - 1) {
obj.productSum = productSum;
}
}
myFinalArr.push(obj);
}
console.log(myFinalArr);// your final Arr
$scope.orders = myFinalArr;
})
In view use this
<div ng-repeat = "orderData in orders">
<div>CustomerId : {{orderData.customerId}}</div>
<div>Name : {{orderData.name}}</div>
<div>Total Product : {{orderData.productCount}}</div>
<div>Total Price : {{orderData.productSum}}</div>
<div>CreatedOn : {{orderData.createdOn}}</div>
</div>
You can do :
<div ng-repeat="order in orders">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
And you'll need a function or a watch to get the total of your products.
If you give me a Plnkr or Jsfiddle link with a working sample I could probably provide a more complete answer if you need.
Happy coding!
try this
<div ng-repeat="(key, value) in orders">
<p>{{value.customerId}}</p>
<p>{{value.createdOn}}</p>
<p>{{value.address.name}}</p>
<div ng-repeat="(key, provalues) in value.products">
<p>{{provalues.quantity}}</p>
<p>{{provalues.productDetails.actualPrice}}</p>
</div>
</div>
To display json Data in html add json filter to your expression like
<div ng-repeat="order in revoluza = (orders | json)">
<div>
customerId={{order.customerId}}
</div>
<div>
name:{{order.address.name}}
</div>
<div>
Total product={{order.products.length}}
</div>
</div>
Please find the clear answer below
html part
<div ng-repeat="(key,value) in accounttypes">
<ul><li ng-repeat="account in value.services">{{account.types}}</li></ul>
</div>
js part
bankservice.findByaccounttype($scope.selectedservice).then(function(results)
{
$scope.accounttypes = results;
});
function bankservice($q)
{
var accountservice=[{"id":"1","title":"Savings Account","services":[{"types":"ATM card request"},{"types":"loan request"}]},
{"id":"2","title":"Current Account","services":[{"types":"cheque book request"},{"types":"ATM card request"}]},
{"id":"3","title":"Demat Account","services":[{"types":"loan request"},{"types":"ATM card request"}]}];
return {
findAll: function() {
var deferred = $q.defer();
deferred.resolve(accountservice);
return deferred.promise;
},
findByaccounttype: function (selectedservice) {
var deferred = $q.defer();
var results = accountservice.filter(function (element) {return selectedservice === element.title;
});
deferred.resolve(results);
return deferred.promise;
}
}
}
I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;
Here is the full code.
HTML part:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this}}</div>
{{/each}}
<p></p>
</script>
JS part
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data= {
"CDataMap" : {
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}
};
$("p").append(template(data));
I want to use this using handlebars js.
When am using it am getting object object display only.
I need the correct code.
The problem with your example is that CDataMap is not an array of objects, so you cannot iterate through them.
This is a valid example:
<script>
(function ($) {
$(function () {
var source = $("#company_template").html();
var template = Handlebars.compile(source);
var data = {
"CDataMap": [{
"name": "Jim Cowart",
"location": {
"city": {
"name": "Chattanooga",
"population": 167674
},
"state": {
"name": "Tennessee",
"abbreviation": "TN",
"population": 6403000
}
},
"company": "appendTo"
}]
};
$("p").append(template(data));
});
})(jQuery);
</script>
And also the p tag or any element you'll use to put the result in must be outside of the template, like this:
<script id="company_template" type="text/x-handlebars-template">
{{#each CDataMap}}
<div>{{this.name}}</div>
<div>{{this.location.city.name}}</div>
{{/each}}
</script>
<p></p>
Handlebar each expects iterative elements. Data which you are supplying needs to be modified.
Below code works
<script id="company_template" type="text/x-handlebarstemplate">
{{#each CDataMap}}
<div>Name : {{this.name}} <br/>
Location: {{this.location.city.name}} <br />
Population: {{this.location.city.population}}
</div>
{{/each}}
</script>
<p></p>
JS side
var data= {
"CDataMap" : [
{
"name": "Jim Cowart",
"location": {
"city": {
"name": "New york",
"population": 494949494
}
}
},
]
};
var templateSource = $("#company_template").html();
template = Handlebars.compile(templateSource);
studentHTML = template(data);
$("p").append(studentHTML);
I'm trying to create a nested listed view with jQuery. The data is in a json file.
Looks like this:
{
"fakultaeten": [
{
"id": "1",
"name": "Carl-Friedrich Gauß",
"institut": [
"Mathematik",
"Informatik"
]
},
{
"id": "2",
"name": "Lebenswissenschaften",
"institut": [
"Biologie/Biotechnologie",
"Chemie/Lebensmittelchemie"
]
},
{
"id": "3",
"name": "Architektur, Bauingenieurwesen und Umweltwissenschaften",
"institut": [
"Department Architektur",
"Department Bauingenieurwesen und Umweltwissenschaften"
]
},
{
"id": "4",
"name": "Maschinenbau",
"institut": [
"test"
]
},
{
"id": "5",
"name": "Elektrotechnik, Informationstechnik, Physik",
"institut": [
"Institut für Datentechnik und Kommunikationsnetze",
"Institut für Elektrische Maschinen, Antriebe und Bahnen"
]
},
{
"id": "6",
"name": "Geistes- und Erziehungswissenschaften",
"institut": [
"test"
]
}
]
}
I'm calling the data like this:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
$.each(data.fakultaeten, function(key,value)
{
$.each(value.institut, function(key1,value1)
{
//console.log(value1)
}
);
}
);
return false;
}
);
</script>
Now I'm a little confused how to display the data in this HTML code.
<div data-role="content">
<h3>Institut für Nachrichtentechnik</h3>
<ul id="taskList" data-role="listview"></ul>
</div>
I know it's a basic problem, but all the other questions and tutorials I found are really confusing me.
I want the nested list look like in this demo: http://jquerymobile.com/demos/1.2.1/docs/lists/lists-nested.html#&ui-page=2-4
it's very simple: just put list value inside the list with id taskList:
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>
Thanks to #JackTurky I got the solution. He was almost right.
This is how I solved it in the end.
<script type="text/javascript" charset="utf-8">
$.getJSON("fakultaeten.js",function(data)
{
var list = $('#taskList');
$.each(data.fakultaeten, function(key,value)
{
var mother = "<li>"+value.name+"<ul>";
$.each(value.institut, function(key1,value1)
{
var son="<li>"+value1+"</li>";
mother+=son;
}
);
mother+="</ul></li>";
list.append(mother);
}
);
list.listview("refresh");
return false;
}
);
</script>