Please help. I'm unable to match JSON parsed values to customer name using Data tables. I was able to populate table column with contact info, but parsed data is identical for both accounts in the table created by code shown. Is there a better way to loop through the data so it displays correctly.
I've seen a few examples of doing this with a simple table, but I would like to keep the sorting capability of Data Tables if possible. Any help will be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Table 01</title>
</head>
<body>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="tableId" class="table table-condensed responsive"></table>
</body>
<script>
var data01 = [
{
"name": "EXAMPLE Mickey",
"due": "2018-11-22T19:00:00.000Z",
"labels": [
{
"name": "Salesperson_1",
"color": "green"
}
],
"pluginData": [
{
"value": "{\"billContact\":\"Mickey Mouse\",\"billCompany\":\"MM Clubhouse\"}",
"access": "shared"
}
]
},
{
"name": "EXAMPLE Carl",
"due": "2018-11-25T19:00:00.000Z",
"labels": [
{
"name": "Salesperson_2",
"color": "yellow"
}
],
"pluginData": [
{
"value": "{\"billContact\":\"Carl Grimes\",\"billCompany\":\"Rick's Group\"}",
"access": "shared"
}
]
}
];
$('#tableId').DataTable({
data: data01,
"columns": [
{"data": "name"},
{"data": "due"},
{"data": "labels.0.name"},
{"data": "pluginData.0.value"},
{"data": function(){
for (var i=0; i < data01.length; i++){
var values = data01[i].pluginData[0].value;
var parsedVal = JSON.parse(values);
var contact = parsedVal.billContact;
return contact;
//console.log(contact);
}
}}
]
});
</script>
</html>
When you pass a function to a column, an argument is passed to that function which represents one entry of your data. So there is no need to iterate over your data by yourself, jQuery is doing that for you.
$('#tableId').DataTable({
data: data01,
"columns": [
{"data": "name"},
{"data": "due"},
{"data": "labels.0.name"},
{"data": "pluginData.0.value"},
{"data": function (row){
let values = row.pluginData[0].value;
let parsedVal = JSON.parse(values);
let contact = parsedVal.billContact;
return contact;
}}
]
});
If you do the iteration by yourself, the function will terminate at the return statement. So everytime the function is called it just see the first entry and return it and stop at that point.
Related
How to output response of type atom/xml feed (from arxiv call) into Jquery DataTable?
I have the datatable working for a simple json from Ajax call to flask server example.
When i try to do it with the xml from an arxiv api response, i cant seem to get it to display in the datatable (though i can just print the raw xml using <pre lang="xml" > or json).
I also tried to convert to json first via python dictionary, but still couldnt get it formatted into datatable as im unsure how to access the properties properly in the Ajax call when theyre deeper than the first level as in the basic example linked.
The HTML in template:
<table id="arxivtable" class="display" style="width:100%">
<thead>
<tr>
<th>title</th>
<th>id</th>
<th>link</th>
<th>author</th>
<th>published</th>
</tr>
</thead>
</table>
I tried via xml :
$('#arxivtable').DataTable({
"ajax": {
// "url": "static/objects2.txt", // This works for the static file
"url": "/get_arxivpapers", // This now works too thanks to #kthorngren
"dataType": "xml",
"type":"GET",
"dataSrc": "{{name}}",
"contentType":"application/atom+xml"
},
"columns": [
{"data": "title"},
{
"data": "link",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '' + data + '';
}
return data;
}
},
{ "data": "id" },
{ "data": "link" },
{ "data": "author" },
{ "data": "journal" },
{ "data": "published" },
{ "data": "summary" }
]
});
JSON from AJAX call:
{
"feed": {
"#xmlns": "http://www.w3.org/2005/Atom",
"link": {
"#href": "http://arxiv.org/api/query?search_query%3Dall%3Aeinstein%26id_list%3D%26start%3D0%26max_results%3D2",
"#rel": "self",
"#type": "application/atom+xml"
},
"title": {
"#type": "html",
"#text": "ArXiv Query: search_query=all:einstein&id_list=&start=0&max_results=2"
},
"id": "http://arxiv.org/api/vehKAQR+bheXtHwJw3qx/OG/XXw",
"updated": "2022-06-14T00:00:00-04:00",
"opensearch:totalResults": {
"#xmlns:opensearch": "http://a9.com/-/spec/opensearch/1.1/",
"#text": "36970"
},
"opensearch:startIndex": {
"#xmlns:opensearch": "http://a9.com/-/spec/opensearch/1.1/",
"#text": "0"
},
"opensearch:itemsPerPage": {
"#xmlns:opensearch": "http://a9.com/-/spec/opensearch/1.1/",
"#text": "2"
},
"entry": [
{
"id": "http://arxiv.org/abs/1801.05533v2",
"updated": "2018-11-22T14:04:43Z",
"published": "2018-01-17T03:05:51Z",
"title": "Einstein-Weyl structures on almost cosymplectic manifolds",
"summary": "",
"author": {
"name": "Xiaomin Chen"
},
"arxiv:comment": {
"#xmlns:arxiv": "http://arxiv.org/schemas/atom",
"#text": "accepted by Periodica Mathematica Hungarica, 14 pages, no figures"
},
"link": [
{
"#href": "http://arxiv.org/abs/1801.05533v2",
"#rel": "alternate",
"#type": "text/html"
},
{
"#title": "pdf",
"#href": "http://arxiv.org/pdf/1801.05533v2",
"#rel": "related",
"#type": "application/pdf"
}
],
"arxiv:primary_category": {
"#xmlns:arxiv": "http://arxiv.org/schemas/atom",
"#term": "math.DG",
"#scheme": "http://arxiv.org/schemas/atom"
},
"category": [
{
"#term": "math.DG",
"#scheme": "http://arxiv.org/schemas/atom"
},
{
"#term": "53D10, 53D15",
"#scheme": "http://arxiv.org/schemas/atom"
}
]
},
{
"id": "http://arxiv.org/abs/0802.2137v3",
"updated": "2008-04-01T04:36:21Z",
"published": "2008-02-15T04:40:56Z",
"title": "",
"summary": ".",
"author": {
"name": ""
},
"arxiv:comment": {
"#xmlns:arxiv": "http://arxiv.org/schemas/atom",
"#text": "18 pages, added Theorem 5"
},
"link": [
{
"#href": "http://arxiv.org/abs/0802.2137v3",
"#rel": "alternate",
"#type": "text/html"
},
{
"#title": "pdf",
"#href": "http://arxiv.org/pdf/0802.2137v3",
"#rel": "related",
"#type": "application/pdf"
}
],
"arxiv:primary_category": {
"#xmlns:arxiv": "http://arxiv.org/schemas/atom",
"#term": "math.DG",
"#scheme": "http://arxiv.org/schemas/atom"
},
"category": [
{
"#term": "math.DG",
"#scheme": "http://arxiv.org/schemas/atom"
},
{
"#term": "53C30; 53C25",
"#scheme": "http://arxiv.org/schemas/atom"
}
]
}
]
}
}
Or the original atom/xml:
<feed xmlns="http://www.w3.org/2005/Atom">
<link href="http://arxiv.org/api/query?search_query%3Dall%3Aeinstein%26id_list%3D%26start%3D0%26max_results%3D2" rel="self" type="application/atom+xml">
<title type="html">ArXiv Query: search_query=all:einstein&id_list=&start=0&max_results=2</title>
<id>http://arxiv.org/api/vehKAQR+bheXtHwJw3qx/OG/XXw</id>
<updated>2022-06-14T00:00:00-04:00</updated>
<opensearch:totalresults xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">36970</opensearch:totalresults>
<opensearch:startindex xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">0</opensearch:startindex>
<opensearch:itemsperpage xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/">2</opensearch:itemsperpage>
<entry>
<id>http://arxiv.org/abs/1801.05533v2</id>
<updated>2018-11-22T14:04:43Z</updated>
<published>2018-01-17T03:05:51Z</published>
<title></title>
<summary>
</summary>
<author>
<name></name>
</author>
<arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom">accepted by Periodica Mathematica Hungarica, 14 pages, no figures</arxiv:comment>
<link href="http://arxiv.org/abs/1801.05533v2" rel="alternate" type="text/html">
<link title="pdf" href="http://arxiv.org/pdf/1801.05533v2" rel="related" type="application/pdf">
<arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="math.DG" scheme="http://arxiv.org/schemas/atom">
<category term="math.DG" scheme="http://arxiv.org/schemas/atom">
<category term="53D10, 53D15" scheme="http://arxiv.org/schemas/atom">
</category></category></arxiv:primary_category></entry>
<entry>
<id>http://arxiv.org/abs/0802.2137v3</id>
<updated>2008-04-01T04:36:21Z</updated>
<published>2008-02-15T04:40:56Z</published>
<title></title>
<summary>
</summary>
<author>
<name></name>
</author>
<arxiv:comment xmlns:arxiv="http://arxiv.org/schemas/atom"></arxiv:comment>
<link href="http://arxiv.org/abs/0802.2137v3" rel="alternate" type="text/html">
<link title="pdf" href="http://arxiv.org/pdf/0802.2137v3" rel="related" type="application/pdf">
<arxiv:primary_category xmlns:arxiv="http://arxiv.org/schemas/atom" term="math.DG" scheme="http://arxiv.org/schemas/atom">
<category term="math.DG" scheme="http://arxiv.org/schemas/atom">
<category term="53C30; 53C25" scheme="http://arxiv.org/schemas/atom">
</category></category></arxiv:primary_category></entry>
</feed>
The End Point:
#app.route('/get_arxivpapers')
def getArxivPapers(name="einstein"):
max_results = 2
searchterm = name.replace("_", " ")
url = 'http://export.arxiv.org/api/query?search_query=all:' + searchterm + '&start=0&' + 'max_results='+ str(max_results)
data = urllib.request.urlopen(url)
# data_dict = xmltodict.parse(data)
# json_data = json.dumps(data_dict)
# print(json_data)
# return jsonify(json_data)
return data.read().decode('utf-8')
I will use your JSON source data instead of the XML, since that is easier to handle in DataTables.
Here is a basic demo, to start with, followed by some explanatory notes:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
</head>
<body>
<div style="margin: 20px;">
<table id="arxivtable" class="display" style="width:100%">
<thead>
<tr>
<th>title</th>
<th>id</th>
<th>link</th>
<th>author</th>
<th>published</th>
<th>summary</th>
</tr>
</thead>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#arxivtable').DataTable({
"ajax": {
url: "YOUR_URL_GOES_HERE",
dataSrc: "feed.entry"
},
"columns": [
{"data": "title"},
{ "data": "id" },
{ "data": "link[].#href" },
{ "data": "author.name" },
{ "data": "published" },
{ "data": "summary" }
]
});
});
</script>
</body>
</html>
Notes
1 - Because you have provided hard-coded HTML column headers, you need to make sure the number of those headers matches the number of columns defined in the DataTable. Alternatively, you can remove the HTML <thead> section and use the DataTables columns.title option.
2 - Your Ajax JSON source data contains an array [ ... ]. DataTables needs to know where this array is located in your JSON response, as part of the Ajax handling option, so that it can iterate over that array. Each element in the array will be used to create a row of HTML table data. The ajax.dataSrc option therefore needs to be set accordingly:
dataSrc: "feed.entry"
Once you have set the above Ajax JSON starting point correctly, then you can use field names for each separate column data value - as shown below.
3 - The author JSON value is actually an object:
"author": {
"name": "Xiaomin Chen"
},
Therefore you need to drill down into that to get the field you want to show in the DataTable:
{ "data": "author.name" },
4 - I removed your column renderer function to keep my initial demo simple, but it can be used to access fields and sub-fields - and concatenate strings and other values as needed (as in your example in the question).
5 - The link JSON value is actually an array of objects. For my basic demo, I just accessed the final entry in that array, and then took the href field:
{ "data": "link[].#href" },
This may not be what you want. You may want to only choose links of a certain type, or choose all links, or something different.
This is where DataTables is limited in what it can handle. It cannot display arbitrary nested JSON values of this type (not surprisingly).
In such cases, you would need to re-structure the JSON, prior to sending it to DataTables - or restructure it in a dataSrc function inside DataTables itself:
"dataSrc": function ( json ) { ...transform and return your JSON here... }
6 - I was not sure what you wanted to display for { "data": "journal" }. I did not see anything called journal in the JSON.
7 - Note that all the source JSON data outside of the feed.entry array is also not available to DataTables. DataTables can only iterate over that outer array. Anything you may also need which is not in that outer array would need to be added to the array, to be accessible to DataTables.
See also Nested object data (arrays) and Nested object data (objects) for more related notes.
The Contract is given above the html file code.
It's basically getting and setting numbers.
I have used promises in my code. Is that the problem?
The ABI is correct as well as the Contract Address.
I have used web3.currentProvider because i am using metamask.
I am a beginner in blockchain.
pragma solidity ^0.5.0;
contract sample {
uint number;
constructor () public {
number = 5;
}
function getNum () public view returns (uint) {
return number;
}
function setNum (uint n) public {
number = n;
}
}
At console, Error:
Uncaught TypeError: Cannot read property 'getNum' of undefined
at index.html:51
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test for Web3</title>
<!--<script src="https://cdn.jsdelivr.net/npm/web3#1.2.1/src/index.min.js"></script>-->
</head>
<body>
<script>
var web3;
web3 = new Web3(web3.currentProvider);
var contract = web3.eth.contract(
[
{
"constant": false,
"inputs": [
{
"name": "n",
"type": "uint256"
}
],
"name": "setNum",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"constant": true,
"inputs": [],
"name": "getNum",
"outputs": [
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
],"0x0c094f6ffbf8dbfde107e819e5060c509eab8951");
contract.methods.getNum().call().then(function(result){
console.log("Number: " + JSON.stringify(result));
});
</script>
</body>
</html>
Looks like you are using 1.X web3.js version. Use var contract = new web3.eth.Contract in this case. See https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html for more info:
new web3.eth.Contract(jsonInterface[, address][, options])
file snapshot_report_js.js:
require([
"dojo/dom",
"dojo/json",
"dojo/store/Memory",
"dijit/tree/ObjectStoreModel",
"dijit/Tree",
"dojo/text!http://localhost:8080/dojo/json_data/snapshot.json",
"dojo/domReady!",
"dojo/_base/json"
], function(dom, json, Memory, ObjectStoreModel, Tree, small){
var stringfied_content = JSON.stringify(small)
var json_parsed_data = JSON.parse(stringfied_content, true)
var json_data = dojo.toJson(json_parsed_data);
// set up the store to get the tree data
var json_store = new Memory({
data: [ json_data ],
getChildren: function(object){
return object.children || [];
}
});
// Create the model
var snapshot_treeModel = new ObjectStoreModel({
store: json_store,
query: {id: 'snapshot'}
});
var snapshot_tree = new dijit.Tree({
model: snapshot_treeModel
}, 'div_snapshot_tree');
snapshot_tree.startup();
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Snapshot</title>
<link rel="stylesheet" href="dijit/themes/claro/claro.css">
<!-- load Dojo -->
<script src="dojo/dojo.js" data-dojo-config="async: true"></script>
<script src="js/snapshot_report_js.js"></script>
</head>
<body class="claro">
<div id="div_snapshot_tree"></div>
</body>
</html>
JSON file:
{
"snapshot_metadata": {
"report_end_at": "2017-10-11 02:03:36",
"environment_name": "DVINST",
"report_start_at": "2017-10-11 01:55:42"
},
"versions": [
{
"id": "version_001",
"instances": [
{
"instance_name": "instance1",
"instance_create_date": "2017-09-18 00:17:52",
"connected_site_count": 4,
"admin_server": "t3://tserver:18300",
"instance_id": 2411,
"instance_type": "OSVC",
"instance_created_by": "None",
"site_capacity": 2,
"sites": [
{
"site_db_id": 395,
"site_name": "zzzz_178",
"site_users": "uc1,uc2,uc3",
"site_id": 89492,
"site_owner": "owner1",
"site_db_name": "site_server2"
},
{
"site_db_id": 395,
"site_name": "site2",
"site_users": "u1, u2, u3",
"site_id": 90447,
"site_owner": "u2",
"site_db_name": "site_server3"
}
]
}
]
}
],
"servers": [
{
"status": null,
"server_id": 13,
"server_name": "db1",
"server_type": "database",
"mount_points": [],
"sites": [],
"db_connections_count": 6,
"health": null,
"admin_servers": null,
"db_sites_connected_count": null
}
]
}
Error on console:
dojo.js:8 Uncaught Error: dijit.tree.ObjectStoreModel: root query
returned 0 items, but must return exactly one at Object.
(ObjectStoreModel.js.uncompressed.js:86) at dojo.js:8 at when
(dojo.js:8) at Object.getRoot
(ObjectStoreModel.js.uncompressed.js:82) at Object._load
(Tree.js.uncompressed.js:897) at Object.postCreate
(Tree.js.uncompressed.js:844) at Object.create
(_WidgetBase.js.uncompressed.js:453) at Object.postscript
(_WidgetBase.js.uncompressed.js:366) at new (dojo.js:8)
at snapshot_report_js.js:178
I don't see anything wrong here, can anybody help?
At first glance your ObjectStoreModel is trying to find root object for tree and as you specified it should have property id equals to snapshot; nothing in your JSON is matching that query.
Secondly, JSON data should bring tree-structured content while your JSON is unstructured; see ObjectStoreModel example how tree data looks like. If you have custom data structure then you need to transform it to be consumed by tree widget thru its model.
Im taking my first steps in json.
There is a huge database where you can query all kinds of statistics regarding my country. Like population
http://px.hagstofa.is/pxen/pxweb/en
Now, if you surf the link above to say population you end up here :
http://px.hagstofa.is/pxen/pxweb/en/Ibuar/Ibuar__mannfjoldi__1_yfirlit__arsfjordungstolur/MAN10001.px/?rxid=f4a21b41-fb7a-45dc-9aec-62ae2d3cea5c
If you select some options you get here :
http://px.hagstofa.is/pxen/pxweb/en/Ibuar/Ibuar__mannfjoldi__1_yfirlit__arsfjordungstolur/MAN10001.px/table/tableViewLayout1/?rxid=f4a21b41-fb7a-45dc-9aec-62ae2d3cea5c
Click the About table and then click "Make this table available in your application"
Now you see a url for posting to json and the json query......
Ive been trying now for few hours to get any kind of data from this url, but I just cant seem to dig it out.
I tried something like this :
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JSON Tutorial</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.getJSON('http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px', function(data) {
console.log(data.variables)
})
</script>
</body>
</html>
Which gave me the next objects.. But I cannot figure out how to get some statistics.....
for example :
female population in 2015
Any help is very much needed.
EDIT :
Few hours later , im still stuck, but im up to this code now :
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JSON Tutorial</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.ajax({
url: 'http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.variables).each(function(index, value) {
console.log(value.values.Alls + ' test ' + value.values );
document.write(value.values[0] + '<br>');
});
}
});
</script>
</body>
</html>
Best regards
The data.variables is an array of four objects. Each object contains four properties, among which are valueTexts and values. So you need a first loop for the first array of four objects, then another loop to find the valueTexts / values pairs:
$.getJSON('http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px', function(data) {
console.log (data.variables);
for( let i = 0; i < data.variables.length; i++ ){
console.info( data.variables[i].text );
for( let k = 0; k < data.variables[i].valueTexts.length; k++ ){
console.log( data.variables[i].valueTexts[k] + ' ' + data.variables[i].values[k] );
}
}
});
Below is a working solution for my question :
There is probably a better way to do this , but I needed a query for the POST, and that gave me results.
Now I just need to make this code spit out the results in csv or xml file.
If anyone has a solution for that , i'd be very thankful.
<html lang="en">
<meta charset="utf-8">
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<script>
var query = {
"query": [
{
"code": "Sveitarfélag",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
},
{
"code": "Aldur",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
},
{
"code": "Ár",
"selection": {
"filter": "item",
"values": [
"18"
]
}
},
{
"code": "Kyn",
"selection": {
"filter": "item",
"values": [
"Alls"
]
}
}
],
"response": {
"format": "csv"
}
};
query = JSON.stringify(query);
$.ajax({
type: "POST",
url: "http://px.hagstofa.is/pxis/api/v1/is/Ibuar/mannfjoldi/2_byggdir/sveitarfelog/MAN02001.px",
data:query,
success: function(json) {
document.write(json);
}
});
</script>
</html>
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>