I have a JSON file and I want to display it in my HTML. But I dont know how to use the syntax for deeply nested objects.
{
"questions": [
{
"question": "Qw1",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
},
{
"question": "Qw2",
"answers": [
{
"answers": "An1",
"value": 25
},
{
"answers": "An2",
"value": 50
},
{
"answers": "An3",
"value": 75
},
{
"answers": "An4",
"value": 100
}
]
}
]
}
I am not trying to use ng-repeat, as I need to access them them one by one.
<div class="main-content" ng-controller="QuestionCtrl">
<div id="Content1">
<h1>Question 1</h1>
<p>{{questions.question[1].answer}}</p>
...........
Ofcourse it doesn't work. How do I acces my information?
There is a working plunker
Using this controller:
.controller('QuestionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.questions = [];
$http
.get("data.json")
.then(function(response){
$scope.questions = response.data.questions;
});
}])
which is loading your data, we can use this
<div class="main-content" ng-controller="QuestionCtrl">
<div id="Content1">
<h1>Question 1</h1>
<p>{{questions[0].question}}</p>
<p>{{questions[0].answers[0]}}</p>
<p>{{questions[0].answers[1]}}</p>
</div>
</div>
Or we can use it like this:
<h1>Question 1</h1>
<p>{{questions[0].question}}</p>
<h2>answer 1</h2>
<p>{{questions[0].answers[0].value}}</p>
<p>{{questions[0].answers[0].answers}}</p>
<h2>answer 2</h2>
<p>{{questions[0].answers[1].value}}</p>
<p>{{questions[0].answers[1].answers}}</p>
which will show the numeric value and answers text
Check it here in action
<div class="main-content" *ngFor="let q of questions">
<h1> {{q.question}}</h1>
<p *ngFor="let ans of q.answers">{{ans.answers}} = {{ans.value}} </p>
</div>
questions is the array, not questions.question, and your JSON does not contain answer properties. Did you try using the correct traversal?
questions[0].answers[0].value
should get you 25.
Related
I am a newbie with Vue and I am trying to run an IF statement inside two v-fors.
Basically I am trying to compare a value from one array of objects to a value of another array of objects and if true, render value from array of objects No 2.
Here is the code.
<div v-bind:class="[isActive ? 'projectsWorkingOnActive' : 'projectsWorkingOnInactive']" v-for="rec in listOfEmployees" v-bind:key="rec.id" >
<div v-for="proj in dummyProjectsData" v-bind:key="proj.id">
<div v-if="rec.name.display_value == proj.task_owner">
<h3>Projects Working On</h3>
<ul>
<li>{{proj.projects_working_on.project_name}}</li>
<li><submitbutton button_label="Hide Projects" #click="toggleClass()"></submitbutton></li>
</ul>
</div>
</div>
</div>
And here are my 2 arrays of objects.
const dummyProjectsData = [
{
ID: "44000005501077",
task_owner: "Denis Denchev",
projects_working_on: [
{
"project_name": "Project-1",
"project_id": "195000002362044"
},
{
"project_name": "Project-2",
"project_id": "195000002362045"
},
{
"project_name": "Project-3",
"project_id": "195000002362046"
},
]
},
{
ID: "44000005501078",
task_owner: "Jake Jones",
projects_working_on: [
{
"project_name": "Project-2",
"project_id": "195000002362044"
},
{
"project_name": "Project-5",
"project_id": "195000002362045"
},
{
"project_name": "Project-3",
"project_id": "195000002362046"
},
]
},
]
And the second array...
const listOfEmployees = [
{
"ID": "44000005527013",
"name": {
"display_value": "Denis Denchev",
"first_name": "Denis",
"last_name": "Denchev",
"prefix": "",
"suffix": "",
}
}
]
What am I doing wrong? It must be something silly that I am missing? Or can I not do if statement taking value from two v-for's ?
The problem is that proj.projects_working_on is an array of multiple projects, but you are trying to access a property on it like an object. Change to something like:
<div v-bind:class="[isActive ? 'projectsWorkingOnActive' : 'projectsWorkingOnInactive']" v-for="rec in listOfEmployees" v-bind:key="rec.id" >
<div v-for="proj in dummyProjectsData" v-bind:key="proj.id">
<div v-if="rec.name.display_value == proj.task_owner">
<h3>Projects Working On</h3>
<ul>
<li v-for="p in proj.projects_working_on" v-bind:key="p.project_id">
{{ p.project_name }}
</li>
<li><submitbutton button_label="Hide Projects" #click="toggleClass()"></submitbutton></li>
</ul>
</div>
</div>
</div>
I am still learning Vue.js. At the moment I am trying to make a simple filtered list method that pulls the data from a json file in Vue. I think that I am having trouble figuring out the correct syntax.
I just cant seem to get it right. Any help is more than welcome :)
This is Vue file:
<template>
<section>
<ul>
<li v-for="product in rings" :key="product">
{{product.title}}
</li>
</ul>
</section>
</template>
<script>
import data from '#/assets/data.json';
export default {
data() {
return {
products: []
}
},
methods: {
computed: {
rings(){
return this.products.filter(product => product.type == 'Ring')
}
}
}
}
</script>
And this is the Json file:
{ "products": [
{
"title": "Ring 1",
"description": "something",
"type": "Ring",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Halskæde 1",
"description": "something",
"type": "Halskæde",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Armbånd 1",
"description": "something",
"type": "Armbånd",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
},
{
"title": "Ørering 1",
"description": "something",
"type": "Ørering",
"year": "2018",
"image": "...",
"price": "2000,00 kr."
}
]
}
You imported the data but never used anywhere inside the component:
import data from '#/assets/data.json';
// notice the data here is just a variable and it has nothing to do with the
// component's data property
export default {
data () {
return {
products: data.products // init products with imported data
}
},
Or with the destructuring syntax:
import { products } from '#/assets/data.json';
export default {
data () {
return {
products // init products with imported data
}
},
First time poster, thanks for the attention.
Using web api to generate object to be consumed by fusioncharts (Multiseries). Object is produced as array of 2 classes (ChartCategories and ChartSeries) output seems fine and is retrieved in angular controller as data. yet after building up $scope.categories and $scope.dataset using data, I am unable to generate the chart with error 'No data to display'.
Partial Html template for chart:
<div id = "Div1">
<fusioncharts
width="400"
height="200"
type="mscolumn2d"
chart="{{attrs}}"
categories="{{categories}}"
dataset="{{dataset}}"
></fusioncharts>
</div>
data retrieved from web api: (copied + pasted)
[
[
{
"category": [
{
"label": "7/18/2014 9:30:01 AM"
},
{
"label": "7/18/2014 9:40:00 AM"
},
{
"label": "7/18/2014 9:50:00 AM"
}
]
},
null,
null
],
[
null,
{
"seriesname": "Free_Memory",
"renderas": "Line",
"data": [
{
"value": "6632"
},
{
"value": "5136"
},
{
"value": "6376"
}
]
},
{
"seriesname": "Page_Life_Exp",
"renderas": "Line",
"data": [
{
"value": "48859"
},
{
"value": "49458"
},
{
"value": "50057"
}
]
}
]
]
and in angular, I set the $scope.categories and $scope.dataset like so: $scope.attr is hard coded for the time being.
$scope.categories = data[0][0];
$scope.dataset = data[1][1];
What is needed in order to generate the graph?
Refer to http://jsfiddle.net/ayanonly1/yh1cvjqw/
I think following changes will make the chart live.
$scope.categories = [data[0][0]];
$scope.dataset = data[1].slice(1);
I have two JSON formats,
JSON -
[
{
"name":"Alex",
"country":"United States"
},
{
"name":"Jaswanth",
"country":"India"
}
]
AngularJS Code -
I was able to display the output
<div ng-repeat="result in results">
{{result.name}} - {{result.country}}
</div>
But if I change my JSON, I am not able to see the output..
[
{
"info": [
"one",
"two",
{
"id": 944589,
"contractYear": 2014
}
],
"country": "India",
"name": "jaswanth"
},
{
"info": [
"three",
"four",
{
"id": 944589,
"contractYear": 2014
}
],
"country": "US",
"name": "jass"
}
]
How to I change my AngularJS code ?
<div ng-init="init();">
<div ng-repeat="result in data">
{{result.name}} - {{result.country}}
<br/>
<div ng-repeat="(k,v) in result.info">
<span ng-if="v.id">The id is: {{v.id}}</span>
<span ng-if="(!v.id)">{{v}}</span>
</div>
<hr/>
</div>
</div>
I am trying to build a demo app with dynamic JSON content that needs to be cached on app load so the urls (router ui) can be accessed immediately.
The "View info for Jack Burton" link at the top only shows his info only after it's been previously loaded (even then, it's screwy):
Example plunker: http://plnkr.co/edit/xIzq8cy4ZsZC9Dz5Cbpv?p=preview
I need to access content about a "person" from other links throughout the app, I'm guessing through in-app urls, not sure what the best practice is for this.
Thanks!
HTML
index.html
<div class="row">
<div class="col-sm-12">
<a ng-href="#/" class="btn-link">Home</a> |
<a ng-href="#/jack-burton">View Info for Jack Burton (Only works after it's cached)</a>
<div class="well" ui-view></div>
</div>
</div>
home.html
<h1>People</h1>
<ul class="list-unstyled">
<li ng-repeat="person in people">
<a ng-href="#/{{ person.url }}" ng-click="setPeopleContent(person)">
{{person.name}}
</a>
</li>
</ul>
person.html
<h1>{{peopleContent.name}}</h1>
<section id="contact" ng-if="peopleContent.hasContact">
<h4>Contact Info</h4>
<p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.address)">
Address: {{item.address}}
</p>
<p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.phone)">
Phone: {{item.phone}}
</p>
<p ng-repeat="item in peopleContent.contact" ng-if="contentExists(item.email)">
Email: {{item.email}}
</p>
</section>
<section id="pastJobs" ng-if="peopleContent.hasPastJobs">
<h4>Past Jobs</h4>
<p ng-repeat="item in peopleContent.pastJobs" ng-if="contentExists(item.job)">
Job: {{item.job}}
</p>
<p ng-repeat="item in peopleContent.pastJobs" ng-if="contentExists(item.jobTitle)">
Title: {{item.jobTitle}}
</p>
</section>
<section id="goals" ng-if="peopleContent.hasGoals">
<h4>Goals</h4>
<ul class="list-unstyled">
<li ng-repeat="item in peopleContent.goals" ng-if="contentExists(item.goal)">
{{item.goal}}
</li>
</ul>
</section>
JSON
{
"people": [
{
"name": "Alexander Supertramp",
"url": "alexander-supertramp",
"contact": [
{
"address": "Alaska"
}
],
"goals": [
{
"goal": "Climb Mt Everest"
},
{
"goal": "Travel in space"
},
{
"goal": "Become a rocket scientist"
}
]
},
{
"name": "Gordon Bombay",
"url": "gordon-bombay",
"pastJobs": [
{
"job": "Hockey Coach",
"jobTitle": "Coach"
},
{
"job": "Hockey Player",
"jobTitle": "Goalie"
}
],
"goals": [
{
"goal": "Win the stanley cup"
},
{
"goal": "Be a cool guy"
}
]
},
{
"name": "Jack Burton",
"url": "jack-burton",
"contact": [
{
"address": "China Town",
"phone": "555-555-getMyTruckBack",
"email": "porkchopexpress#gmail.com"
}
],
"pastJobs": [
{
"job": "Porkchop Express Driver",
"jobTitle": "Truck Driver"
}
],
"goals": [
{
"goal": "Get his truck back"
},
{
"goal": "Stay alive"
},
{
"goal": "Get with Kim Cattrall"
}
]
},
{
"name": "Eric Roberts",
"url": "eric-roberts",
"contact": [
{
"address": "New York City",
"email": "ambulance911#gmail.com"
}
],
"goals": [
{
"goal": "Become a comicbook artist"
},
{
"goal": "Find that woman from the street"
},
{
"goal": "Stay alive"
},
{
"goal": "Don't get run over by an evil ambulance"
}
]
}
]
}
JS
var myapp = angular.module('demoApp', ["ui.router"])
myapp.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: "/",
templateUrl: "home.html"
})
.state('person', {
url: "/:person",
templateUrl: "person.html"
})
$urlRouterProvider.otherwise("/")
});
function MainController($scope, $http, $stateParams) {
$http.get('demo-data.json', { cache: true}).success(function(data){
$scope.people = data.people;
});
$scope.person = $stateParams.person;
$scope.setPeopleContent = function(person) {
$scope.peopleContent = person;
$scope.peopleContent.hasContact = ($scope.peopleContent.contact instanceof Array);
$scope.peopleContent.hasPastJobs = ($scope.peopleContent.pastJobs instanceof Array);
$scope.peopleContent.hasGoals = ($scope.peopleContent.goals instanceof Array);
};
// Checks if contentValue is undefined / exists
$scope.contentExists = function(contentValue) {
if(contentValue != undefined) {
return true;
}
};
};
You should use either localStorage or sessionStorage here is more info: link
Here is one example of how I use it with angular:
Note I'm storing date to when was last time I've saved data to storage (and if data is too old I get data again from server and save it to storage)
var retreivedStorageData = JSON.parse(window.sessionStorage.getItem("basicUserInfo"));
if (retreivedStorageData) {
var differenceInMs = Math.abs(new Date() - new Date(retreivedStorageData.date));
// check how old is data
if (differenceInMs <= 60 * 1000) {
$scope.ImageUrl = retreivedStorageData.item.ImageUrlSmall;
$scope.UserName = retreivedStorageData.item.Name;
} else {
//if it's too old get it from server
getDataFromServer();
}
} else {
getDataFromServer();
}
function getDataFromServer() {
$http.get("/Profile/GetUserBasicInfo/")
.success(function(result) {
/*More code here*/
if (typeof (window.Storage) != "undefined") {
var storageData = JSON.stringify({ item: result, date: new Date() });
window.sessionStorage.setItem("basicUserInfo", storageData);
}
});
}