I have this JSON object being retreived from the server
{
"Totals": {
"TotalNotifications": 10,
"TotalUnreadNotifications": 5
},
"NotificationData": [{
"NotificationId": 1,
"NotificationType": "Alert",
"NotificationName": "Low Battery",
"NotificationDate": "2014-09-08T19:38:57.659",
"NotificationRead": false,
"NotificationActive": true,
"AlertData": {
"AlertType": "Battery",
"AlertSeverity": "Critical"
}
}, {
"NotificationId": 2,
"NotificationType": "Dtcprimary",
"NotificationName": "Mass or Volume Air Flow",
"NotificationDate": "2014-09-01T12:00:00.000",
"NotificationRead": false,
"NotificationActive": true,
"DtcData": {
"DtcCode": "P0101",
"Vehicle": "2000 Cadillac Deville 4.6L",
"DtcDescription": "Mass or Volume Air Flow A Circuit Range Performance",
"ShortDescription": "Ceat ame aut placcat doluptus, quo berum quiandae quid quissim agnimus danimol uptae. Neque si omnis sequo torabori tem nobitatet arcit aut incimaxim fugia sitatium",
"IdentifixId": "Click <a target=\"_blank\" href=\"https://www.google.com\">here</a> to request a list of top fixes."
}
}, {
"NotificationId": 3,
"NotificationType": "Dtcsecondary",
"NotificationName": "Mass or Volume Air Flow",
"NotificationDate": "2014-08-01T12:00:00.000",
"NotificationRead": true,
"NotificationActive": false,
"DtcData": {
"DtcCode": "P0101",
"Vehicle": "2000 Cadillac Deville 4.6L",
"DtcDescription": "Mass or Volume Air Flow A Circuit Range Performance",
"ShortDescription": "Ceat ame aut placcat doluptus, quo berum quiandae quid quissim agnimus danimol uptae. Neque si omnis sequo torabori tem nobitatet arcit aut incimaxim fugia sitatium",
"TopReportedFix": "Replace Air Intake Boot",
"FrequentlyReportedFixes": "<ul><li>Cleaned Mass Air Flow (MAF) Sensor</li><li>Programmed Powertrain Control Module (PCM)</li></ul>",
"AlsoReportedFixes": "<ul><li>Cleaned Mass Air Flow (MAF) Sensor</li><li>Cleaned throttle body</li><li>Flushed fuel tank w/P0171, P0174</li></ul>"
}
}, {
"NotificationId": 4,
"NotificationType": "Recall",
"NotificationName": "Mass or Volume Air Flow A Circuit Range Performance",
"NotificationDate": "2014-09-01T12:00:00.000",
"NotificationRead": false,
"NotificationActive": true,
"RecallId": 31234
}]
}
When I loop over the Notification object nothing happens. When I try regular handlebars it works just fine, http://jsbin.com/lemafe/1/edit
Here is how I'm looping in my Emberjs component. items is the name of the property after it gets passed into the component.
{{alerts-dashboard items=model}}
{{#each items}}
{{Totals.TotalUnreadNotifications}} // this outputs the number 5 as expected
{{#each NotificationData}}
{{NotificationId}} //this doesn't get outputted because the loop never happens
{{/each}}
{{/each}}
Why doesn't it work in Emberjs?
You need to use {{#each item in items}}.
{{#each item in items}}
{{item.Totals.TotalUnreadNotifications}}
{{#each item.NotificationData}}
{{NotificationId}}
{{/each}}
{{/each}}
I have created a JSBin example.
Edit:
Here is my edited JSBin showing that it also works if you use the lowercase name for notificationData, like mentioned in this related answer, that I have found here on SO.
{{#each model}}
<li>{{Totals.TotalUnreadNotifications}}</li>
<ul>
{{#each notificationData}}
<li>Type: {{NotificationType}}</li>
{{/each}}
</ul>
{{/each}}
Related
I do have 2 collections - events and bookings.
Events contain a collection of events. Bookings collection contain just the eventId of the event which we need to book and the current loggedin user.
I got the events which was not booked, using lodash
const results = _.differenceWith(
eventsArr,
bookingArr,
(event, booking) => event.id == booking.eventId
);
How do we select the booked events?
I was tying to filter the events array based on the eventID of the other array, but didnt work!
Any ideas will be of great help!
EDIT:
Adding the structure too, ( and thanks for the quick help, adding full structure of that can help another person, also the backend was firebase )
The events array
{
"-LWSkZgZ-e84Aq7EnvOo" : {
"date" : "January 17",
"description" : "Lorem ipsum dolor amet fashion axe cray pour-over green juice. Salvia everyday carry viral, PBR&B pop-up polaroid direct trade gochujang hot chicken disrupt gentrify quinoa crucifix pabst cred. ",
"imageUrl" : "https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
"location" : {
"lat" : 77.88,
"lng" : 66.65,
"name" : "Texas CA"
},
"name" : "MetalBone",
"ticketsAvailable" : true
},
"-LWSkbMLqDlpTgcgFHy2" : {
"date" : "January 18",
"description" : "Mlkshk brooklyn gastropub paleo bicycle rights. Man bun brunch helvetica food truck whatever tousled vegan vinyl pug cred mumblecore. ",
"imageUrl" : "https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500",
"location" : {
"lat" : 32.77,
"lng" : 96.7,
"name" : "Dallas SF"
},
"name" : "Big Day Out",
"ticketsAvailable" : true
},
The bookings array
{
"-LWdae8S33xrHfLetvT7" : {
"eventId" : "-LWSkZgZ-e84Aq7EnvOo",
"userMail" : "test#test.com"
},
"-LWdj2UDTwVV6_71Bcyd" : {
"eventId" : "-LWTraS93uC37S21syqP",
"userMail" : "test#test.com"
}
}
You can use _.intersectionWith() to find events/bookings with common id:
const results = _.intersectionWith(
eventsArr,
bookingArr,
(event, booking) => event.id === booking.eventId
);
This example takes, the data you've added, converts it to an array format, and uses _intersectionWith() to find booked events:
const events = {"-LWSkZgZ-e84Aq7EnvOo":{"date":"January 17","description":"Lorem ipsum dolor amet fashion axe cray pour-over green juice. Salvia everyday carry viral, PBR&B pop-up polaroid direct trade gochujang hot chicken disrupt gentrify quinoa crucifix pabst cred. ","imageUrl":"https://images.pexels.com/photos/1047940/pexels-photo-1047940.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":77.88,"lng":66.65,"name":"Texas CA"},"name":"MetalBone","ticketsAvailable":true},"-LWSkbMLqDlpTgcgFHy2":{"date":"January 18","description":"Mlkshk brooklyn gastropub paleo bicycle rights. Man bun brunch helvetica food truck whatever tousled vegan vinyl pug cred mumblecore. ","imageUrl":"https://images.pexels.com/photos/849/people-festival-party-dancing.jpg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=500&w=500","location":{"lat":32.77,"lng":96.7,"name":"Dallas SF"},"name":"Big Day Out","ticketsAvailable":true}}
const bookings = {"-LWdae8S33xrHfLetvT7":{"eventId":"-LWSkZgZ-e84Aq7EnvOo","userMail":"test#test.com"},"-LWdj2UDTwVV6_71Bcyd":{"eventId":"-LWTraS93uC37S21syqP","userMail":"test#test.com"}}
const result = _.intersectionWith(
_.map(events, (v, id) => ({ id, ...v })),
_.values(bookings),
(event, booking) => event.id == booking.eventId
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
I am trying to complete an assignment for class and I can't figure out why my json is not working as intended. The specifics of the assignment are:
Using React.js as a base, make a data-driven map application that
contains this set of interactions:
Data
A .json file with at least five points of interest with this
data: x and y locations, name of the location, a url to a picture of
the location (included in your project), and a description of the
location.
Layout
Project should have two panels: a left-side panel lists all the names
of the locations. A right-side should display all of the locations (as
a set of makers) on an IMAGE (it doesn't have to be a map like google
maps). Yes, this means you could make a fantasy map or something else.
Hidden initially should also be a series of popups that will be made
visible in the interaction with the project.
Interaction
When clicking on an an a location name on the left bar -> highlight
the corresponding marker on the map. When clicking on a marker on a
map -> highlight the location name in the left bar AND display a popup
above the map that shows all the related information.
Final points (10pts): Adjust the data so each location has a set of
tags (i.e. "food", "hiking"). Create a third component that lists
these tags. Clicking on one of these tags will "filter" the data
displayed so that only the entries with those tags can be seen in the
listing on the map.
Now I think that I have everything, but when I try to run this I receive the error "Unhandled Rejection (SyntaxError) Unexpected end of JSON input". From what I can tell from looking into the problem it's something with parsing the json into HTML but I can't figure out why I'm getting this problem.
What I have:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import List from "./List";
import Points from "./Points";
import Tags from "./Tags";
import "./styles.css";
class App extends Component {
constructor() {
super();
this.state = {
points: {
data: [
{
id: 0,
x: 0,
y: 0,
name: "name",
url: "url"
}
]
},
selected: "none",
tag: "none"
};
//load in the JSON
fetch("data/data.json")
.then(result => result.json())
.then(data => {
//sets the json data to this.state.points
this.setState({ points: data });
});
}
render() {
console.log(this.state.points.data[this.state.selected]);
return (
<div className="App">
<List
selected={this.state.selected}
onSelection={choice => {
this.changeSelection(choice);
}}
pointInfo={this.state.points.data}
/>
<Points
onSelection={choice => {
this.changeSelection(choice);
}}
selected={this.state.selected}
selectionChoice={this.state.points.data[this.state.selected]}
pointInfo={this.state.points.data}
/>
</div>
);
}
//changes the selected value in state
//value of selected is send to Points and List
changeSelection(num) {
this.setState({ selected: num });
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
And I don't know if the issue could stem from the actual json file, but my json is:
{
"data": [
{
"id": 0,
"x": 500,
"y": 500,
"name": "Pittsburgh",
"url": "./images/Pittsburgh.jpg",
"description": "Pittsburgh is a city in western Pennsylvania at the junction of 3 rivers. Its Gilded Age sites, including the Carnegie Museum of Natural History, the Carnegie Museum of Art and the Phipps Conservatory and Botanical Gardens, speak to its history as an early-20th-century industrial capital. In the North Shore neighborhood are the modern Andy Warhol Museum, Heinz Field football stadium and PNC Park baseball stadium.",
"tag": "historical"
},
{
"id": 1,
"x": 700,
"y": 220,
"name": "Indianapolis",
"url": "./images/Indianapolis.jpg",
"description": "Indianapolis is the capital and most populous city of the U.S. state of Indiana and the seat of Marion County. As of 2017, Indianapolis is the third most populous city in the American Midwest and 16th most populous in the U.S., with an estimated population of 863,002.",
"tag": "governmental"
},
{
"id": 2,
"x": 450,
"y": 100,
"name": "Garland",
"url": "./images/Garland.jpg",
"description": "Garland is a city in the U.S. state of Texas. It is a large city located northeast of Dallas and is a part of the Dallas–Fort Worth metroplex. It is located almost entirely within Dallas County, except a small portion located in Collin and Rockwall Counties.",
"tag": "historical"
},
{
"id": 3,
"x": 480,
"y": 240,
"name": "Tampa",
"url": "./images/Tampa.jpg",
"description": "Tampa is a city on Tampa Bay, along Florida’s Gulf Coast. A major business center, it’s also known for its museums and other cultural offerings. Busch Gardens is an African-themed amusement park with thrill rides and animal-viewing areas. The historic Ybor City neighborhood, developed by Cuban and Spanish cigar-factory workers at the turn of the 20th century, is a dining and nightlife destination.",
"tag": "historical"
},
{
"id": 4,
"x": 650,
"y": 100,
"name": "Sacramento",
"url": "./images/Sacramento.jpg",
"description": "Sacramento, capital of the U.S. state of California, lies at the confluence of the Sacramento River and American River. The district of Old Sacramento harkens back to the city’s Gold Rush era, with wooden sidewalks and wagon rides. One of several museums in Old Sacramento, the California State Railroad Museum depicts the construction of the Transcontinental Railroad, one of the country’s earliest technological feats.",
"tag": "historical"
}
]
}
Is there something that I'm just missing here or have I completely missed the mark on what I'm trying to do?
I have tried the filter logic from angular to one of the unordered list.
But, the search filter is working after typed 3 characters of the name, sometimes giving wrong search results.
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter :searchString">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
JSON:
{
"People":[
{
"name":"Andrew Amernante",
"rating":3,
"img":"http://www.fillmurray.com/200/200",
"Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
},
{
"name":"Frank Wang",
"rating":5,
"img":"http://www.fillmurray.com/200/201",
"Description":"Before errors, mails were only pressures. This is not to discredit the idea that a magic is the prose of anelizabeth. This could be, or perhaps some posit the outmost coil to be less than dedal. Some assert that those treatments are nothing more than carp.",
"Likes":[
"Frank",
"Manchester United",
"Football",
"Programming"
],
"Dislikes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
]
},
{
"name":"Sissi Chen",
"rating":5,
"img":"http://www.fillmurray.com/200/202",
"Description":"Aaah! Natural light! Get it off me! Get it off me! Oh, loneliness and cheeseburgers are a dangerous mix. D'oh. Here's to alcohol, the cause of all life's problems.",
"Likes":[
"Cats",
"the beach",
"Chopin",
"Blue things"
],
"Dislikes":[
"Birds"
]
},
{
"name":"Diego Garcia",
"rating":2,
"img":"http://www.fillmurray.com/200/204",
"Description":"Facts are meaningless. You could use facts to prove anything that's even remotely true! I prefer a vehicle that doesn't hurt Mother Earth. It's a gocart, powered by my ownsense of selfsatisfaction. You don't win friends with salad.",
"Likes":[
"Talking Spanish",
"Spanish food",
"Spanish things",
"Football"
],
"Dislikes":[
"Not talking spanish",
"Chopin"
]
},
{
"name":"Fuad Rashid",
"rating":4,
"img":"http://www.fillmurray.com/200/206",
"Description":"Glutenfree cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
Here is the plnkr code.
Ex: Start typing 'si', you will end up with two results where first one(frank wang) is not correct.
And, this is the reference plnkr where I'm referring for.
You would need to specify which object property, in this case name for the filter to filter against:
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter: { name: searchString }">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
You would need to set the initial value of searchString to an empty string as well to match against all people when no text has been entered.
$scope.searchString = '';
Here is a Plunker demonstrating the functionality.
Hopefully that helps!
You can create your own customized filter to specify on which property you need to search:
$scope.searchTextByName = function(artist){
if($scope.searchText !== undefined){
if(artist.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) > -1 ){
return artist;
}
}
}
Otherwise, it will match on all JSON value of single people object with your searchText key.
Currently I am pulling information from two JSON files stored online. My goal is to display the information stored within these files in my app, using one for content and the other for attributes that can apply to the content, like background and font color.
My main issue is this:
I am trying to fill an ObservableArray with other arrays, and then reference the information stored within each of those within the XML file. A fairly simple idea, yes?
Content JSON
{
"content": [
{
"description": "If you’ve been dreaming about owning a customizable smartwatch, the modular watch that London-based Blocks promised is now available ...",
"image": "https:\/\/cdn3.vox-cdn.com\/thumbor\/mOV6mjP_AI50YsQDbQ81444XEB4=\/0x21:2520x1701\/1310x873\/cdn0.vox-cdn.com\/uploads\/chorus_image\/image\/49811865\/hero-bg_2x.0.0.jpg",
"created_utc": "1467036570",
"title": "The Blocks modular smartwatch can now be pre-ordered",
"type": "04",
"url": "http:\/\/www.theverge.com\/circuitbreaker\/2016\/6\/9\/11894152\/blocks-modular-smartwatch-pre-order"
},
{
"description": "At Lenovo TechWorld, we got a glimpse at the Moto Z's developer mod kit and how it can be used to make wacky and weird slip-on attachments.",
"image": "http://img.youtube.com/vi/A0YFmMEjXP0/mqdefault.jpg",
"created_utc": "1467032545",
"title": "Lenovo's Experimental Moto Mods",
"feedid": "03",
"url": "https://www.youtube.com/watch?v=A0YFmMEjXP0"
},
{
"description": "",
"image": "https://pbs.twimg.com/media/CkmZk8QXIAEKnTF.jpg",
"created_utc": "1467035885",
"title": "The US just approved six airlines to begin flying to Cuba",
"feedid": "02",
"url": "http://www.theverge.com/2016/6/10/11903034/us-cuba-airlines-american-southwest-frontier-jetblue"
},
{
"description": "'Texts from Hillary' photo raised questions about Clinton email habits at State Department",
"image": "https://cdn1.vox-cdn.com/thumbor/COJRCv7KVVwj3uO5qt1XHZ5F02Y=/0x82:3010x2089/1280x854/cdn0.vox-cdn.com/uploads/chorus_image/image/49821307/AP_16147060028688.0.0.jpg",
"created_utc": "1467036728",
"title": "The photo went viral enough to catch the eye of the State Department.",
"feedid": "01",
"url": "https://www.facebook.com/verge/posts/1116679778368364"
},
{
"description": "One of the benefits of being (somewhat) bilingual is you get double the internet content. I feel very blessed to be able to enjoy both American internet full of...",
"image": "https://cdn2.vox-cdn.com/thumbor/gM8KeNQUzto6fmdot7wfA_q9jSs=/0x0:3000x2000/1310x873/cdn0.vox-cdn.com/uploads/chorus_image/image/49820235/GettyImages-499350590.0.jpg",
"created_utc": "1467036669",
"title": "If you drop an ant from the top of the Empire State Building, will it die?",
"feedid": "04",
"url": "http://www.theverge.com/tldr/2016/6/10/11894028/ant-dropped-from-empire-state-building-science-experiment"
},
{
"description": "Tesla has denied that its cars suffer from suspension defects, suggesting that comments from the US National Highway Traffic Safety Administration (NHTSA) have been misinterpreted.",
"image": "https://cdn2.vox-cdn.com/thumbor/IAh-NZAZzH_AwdO2ubVMKlZkB2Y=/187x0:2212x1350/1310x873/cdn0.vox-cdn.com/uploads/chorus_image/image/49819011/model-s-photo-gallery-06.0.0.jpg",
"created_utc": "1467042890",
"title": "Tesla denies Model S suspension defects, chides journalist in blog post",
"feedid": "04",
"url": "http://www.theverge.com/circuitbreaker/2016/6/9/11894152/blocks-modular-smartwatch-pre-order"
}
]
}
Sources and Attributes JSON
{
"sources": [
{
"category":"news",
"subject":"technology",
"adsenabled":true,
"bannerimgsrc":"https://www.camplaurel.com/images/pagegraphics/home/l-header-bg.jpg",
"rowbgimgsrc":"https://www.camplaurel.com/images/pagegraphics/home/l-header-bg.jpg",
"titlebgcolor":"#ffffff",
"row2ndcolor":"#000000",
"rowtxtcolor":"#e22805",
"rowbgcolor":"#ffffff",
"iconsrc": "https://pbs.twimg.com/profile_images/615501837341466624/I4jVBBp-.jpg",
"id": 1,
"shortname": "verge",
"name": "The Verge"
},
{
"category":"news",
"subject":"leisure",
"adsenabled":true,
"bannerimgsrc":"https://pbs.twimg.com/profile_banners/275686563/1433249898/1500x500",
"rowbgimgsrc":"null",
"titlebgcolor":"#ece4d1",
"row2ndcolor":"#9b4e34",
"rowtxtcolor":"#6b2e1e",
"rowbgcolor":"#ece4d1",
"iconsrc": "https://camo.githubusercontent.com/b13830f5a9baecd3d83ef5cae4d5107d25cdbfbe/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f3732313033382f313732383830352f35336532613364382d363262352d313165332d383964312d3934376632373062646430332e706e67",
"id": 1,
"shortname": "Laurel South",
"name": "Camp Laurel South, Mains Premier Sleep Over Camp"
}
]
,
"feeds": [
{
"hidden": false,
"iconsrc": "http://icons.iconarchive.com/icons/danleech/simple/1024/facebook-icon.png",
"id": 1,
"notistat": "Sound and Text",
"sourceid":1,
"title": "The Verge Facebook"
},
{
"hidden": false,
"iconsrc": "http://icons.iconarchive.com/icons/danleech/simple/1024/facebook-icon.png",
"id": 2,
"notistat": "Sound and Text",
"sourceid":1,
"title": "The Verge Twitter"
},
{
"hidden": false,
"iconsrc": "http://icons.iconarchive.com/icons/danleech/simple/1024/facebook-icon.png",
"id": 3,
"notistat": "Sound and Text",
"sourceid": 1,
"title": "The Verge Youtube"
},
{
"hidden": false,
"iconsrc": "http://icons.iconarchive.com/icons/danleech/simple/1024/facebook-icon.png",
"id": 4,
"notistat": "Sound and Text",
"sourceid": 1,
"title": "The Verge RSS"
}
]
}
My JavaScript file uses a variable listed as bindingContext as the bindingContext of the page. myArray is a part of the bindingContext, and is being pushed into by my JSON mapping and loading functions, at least in theory.
var Observable = require('data/observable').Observable;
var ObservableArray = require('data/observable-array').ObservableArray;
var http = require("http");
var moment = require('moment');
var frameModule = require('ui/frame');
var bindingContext = new Observable({
title: "Loading...",
myArray: new ObservableArray()
});
function pageLoaded(args) {
var page = args.object;
page.bindingContext = bindingContext;
loadSources();
loadFeeds();
loadContent();
}
function loadContent() {
var content = [];
http.getJSON("http://www.doesntmatter.com/jsoncontent.php")
.then(function (r) {
bindingContext.title = 'Notifications Up to Date';
r.content.map( function(item) {
item.friendlyTime = moment(item.created_utc * 1000).fromNow();
content.push(item);
});
bindingContext.myArray.push(content);
console.log("content loaded.");
});
}
function loadSources() {
var mysources = [];
http.getJSON("http://www.secrets.com/jsonsource.php")
.then(function (r) {
r.sources.map( function(item) {
mysources.push(item);
console.log(item.name);
});
});
bindingContext.myArray.push(mysources);
console.log("sources loaded!");
};
}
//LoadSources should add all listed Sources into an array of sources, which is then pushed into the larger "myArray" which allows coloration and other css items to be determined for each object within an array
function loadFeeds() {
var myfeeds = [];
http.getJSON("http://www.shhhhhhhh.com/jsonsource.php")
.then(function (r) {
r.feeds.map( function(item) {
myfeeds.push(item);
});
bindingContext.myArray.push(myfeeds);
console.log("feeds loaded.");
});
}
//LoadFeeds should add all listed feeds into an array of feeds, which is also loaded into "myArray", which can then be drawn from to create individual color schemes
exports.pageLoaded = pageLoaded;
The part I am having a lot of trouble with is correctly referencing the array, subarrays, and contents of each within both the JavaScript file and the XML file due to a somewhat rusty knowledge of both languages.
<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="pageLoaded">
<Page.actionBar>
<ActionBar title="Notify">
</ActionBar>
</Page.actionBar>
<ListView items="{{ myArray }}" itemTap="itemTap" loadMoreItems="loadMoreItems" class="containter">
<ListView.itemTemplate>
<GridLayout rows="21,*,*" columns="90,*" width="*" height="*" >
<!-- <Image row="0" col="0" colSpan="1" rowspan="3" src="{{ getItem[2].image }}" /> -->
<!-- <Label row="0" col="1" colSpan="1" class="time" text="{{ friendlyTime }}" textAlignment="right" /> -->
<!-- <Label row="1" col="1" colSpan="1" class="title" text="{{ content.title }}" margin="1" textWrap="true" /> -->
<!-- <Label row="2" col="1" colSpan="1" class="description" text="{{ description }}" textWrap="true" backgroundColor="{{ this is where I would want to reference the contents of the subarrays}}" /> -->
</GridLayout>
</ListView.itemTemplate>
</ListView>
</Page>
Again, just to reiterate: I have an ObservableArray which is part of the bindingContext of the page. This is being filled with other arrays, which are each filled with information I want to apply to my XML file. How can I reference this information using the correct syntax for both JavaScript and XML?
I think you actually need to rethink your design. ;-)
First issue that occurred to me is that myArray[0] can end up being content, sources or feeds. Just because you ran the code:
loadSources();
loadFeeds();
loadContent();
In a synchronous fashion, does not guarentee the result order; each one of those loads the file from a ASYNC source (i.e. in this case http); depending on which one of those ASYNC sources actually responds with its data first, it is which one will get put into your MyArray first. ;-)
Your second issue is that
<ListView items="{{ myArray }}"
Will only create three of your GridLayout templates; because their are only three myArray items (i.e the content, feeds, source) based on your data; I'm pretty sure you aren't just wanting to show three line items.
Now the question becomes do you need each item to link to a source to a feed, or do you just want to combine all three types and display each type of line item differently based on which type it it.
New to angular and developing a simple page just to learn the inner workings. What I have is a div that display name price and description along with a button and a full image. What I'm trying to do is underneath that full image display 2-3 additional images. The problem is the same full image is displaying again and none of the additional images are displaying.
Here is the angular
(function () {
var app = angular.module('gemStore', []);
app.controller('StoreController', function () {
this.products = gems;
});
var gems = [
{
name: 'Defmei',
price: 2.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: false,
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
},
{
name: 'Sijoi',
price: 5.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: true,
images: [
{
image: "Images/image4.jpg",
image: "Images/image3.jpg",
image: "Images/image2.jpg"
}
]
}
]
})();
Here is the HTML
<body data-ng-controller="StoreController as store" >
<div class="display" data-ng-repeat="product in store.products">
<h1>{{product.name}}</h1>
<h2>{{product.price | currency}}</h2>
<p> {{product.description}} </p>
<img class="imageStyles" data-ng-src="{{product.images[0].image}}"/>
<br />
<div data-ng-repeat="image in product.images">
<img data-ng-src="{{image.image}}" class="thumbs" />
</div>
<button data-ng-show="product.canPurchase">Add to cart</button>
</div>
</body>
That image object seems "broken", you're practically redefining the image attribute 3 times.
In javascript, objects have a syntax like { attribName1: attValue1, attribName2: attValue2 ...}
What you're creating here:
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
Is an array with 1 item, which is an object, with 1 property, "image", with a value of... "Images/image3.jpg" maybe (or whatever, I wouldn't be surprised if double-defining attributes like this was in fact undefined behaviour).
What you probably want instead is either an array with 3 elements, or an object with 3 distinct attributes, ie:
images: [
{
"image1": "Images/image1.jpg",
"image2": "Images/image2.jpg",
"image3": "Images/image3.jpg"
}
]
You can iterate through array members and object attributes too with ng-repeat, but you have to change your code accordingly.
Your images array only has one item in it with image defined three times. Change it like the following so that there are three separate items and it should work.
images: [
{image: "Images/image4.jpg"},
{image: "Images/image3.jpg"},
{image: "Images/image2.jpg"}
]