get nested JSON object in angular js - html

I'm having a AngularJS spa and want to fetch files from a JSON, which works good so far.
var app = angular.module("MyApp", []);
app.controller("TodoCtrl", function($scope, $http) {
$http.get('todos.json').
success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
alert("Error");
});
});
and bind it to repeat a list.
<ul ng-repeat="post in posts">
<li>
<b>Name : </b> {{post.name}} <br>
<b>Adress/street :</b> {{post.address.street}}
</li>
</ul>
my problem ist, what if I have nested another object inside the JSON:
"adress": [
{
"street": "somewhat street",
"town": "somewhat town"
}]
My attempt post.adress.street does not work. Any suggestions?

Since address is an array, you have 2 options.
First option:
Use the array notation to access only one of the items in the array. For example:
<ul ng-repeat="post in posts">
<li>
<b>Name : </b> {{post.name}} <br>
<b>Adress/street :</b> {{post.address[0].street}}
</li>
</ul>
Second option:
Iterate over all the address items using another ng-repeat:
<ul ng-repeat="post in posts">
<li>
<b>Name : </b> {{post.name}} <br>
<div ng-repeat="address in post.address">
<b>Adress/street :</b> {{address.street}}
</div>
</li>
</ul>

Related

Create full menu based on Json file

I have a fully functional menu (static), as im going to post, i want to replicate it based on what i get from a json file, i mean, create menu based on json file.
heres what i want as a menu:
html:
<div class="menu-container" >
<div class="menu">
<nav class="navbar-toggleable-md">
<div id="toggle" class="navbar-toggler"><a></a>
</div>
</nav>
<ul id="my_styles" class="rowcenter" >
<li>
<a role="button" class="button button4 menu-button" ><i role="button" class="icon-ambientais fs1 icon menu-button"></i><span class="button-text rowcenter menu-button">menu1</span></a>
<ul class="menu-list">
<li>
<i style="color: white" class="icon-ambientais fs1"></i>submenu
<ul>
<li>{{ 'submenu</li>
<li>submenu</li>
<li>{{ 'Imagens' | translate }}</li>
</ul>
</li>
<li>
<i style="color: white" class="icon-gestao-ambient fs1"></i>submenu3
<ul>
<li>submenu2</li>
<li>submenu2</li>
<li>submenu2</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
i have javascript to make it work.
I was searching for some help, because i cant figute it out..
i found that example, but i can't make it look like what i need.
https://www.codeproject.com/Articles/311758/Building-Menu-from-JSON
(passing the json obj to json file)
but i can't make it work like the menu i have.. if i change, for example, <ul> to <ul class="bla"> on this one, it breaks.
then i found that: Creating a Menu from JSON
but no success..
heres my trying code:
on html i just call
my typescript file:
.ts
ngOnInit() {
this._menu.getMenu()
.subscribe( res => {
let data = res;
console.log(data);
var getMenuItem = function (itemData) {
var item = $("<li>")
.append(
$("<a>", {
href: itemData.link,
html: itemData.name
}));
if (itemData.sub) {
var subList = $("<ul>");
$.each(itemData.sub, function () {
subList.append(getMenuItem(this));
});
item.append(subList);
}
return item;
};
var $menu = $("#menu");
$.each(data.menu, function () {
$menu.append(
getMenuItem(this)
);
});
$menu.menu();
});
}
had somebody done something like this before?
if someofyou have a working example with one menu item and submenu, even without img, i would appreciate it.
thank you.
Ok i got the solution!
Having al lthe css and html done, i've just got the JSON file to array that way:
this._menu.getMenu()
.subscribe( res => {
let data = res;
console.log(data);
this.arr = data;
this.arr = (<any>Object).values(data);
});
Then, on html i just picked the menus and sub menus names / links / icons, and ngfor them into the already made tags:
<li *ngFor="let item of arr[0]; let i = index;">
<a role="button" class="button button4 menu-button" ><i role="button" class={{item.class}}></i><span class="button-text rowcenter menu-button">{{item.name}}</span></a>
<ul class="menu-list" *ngIf=item.sub>
<li *ngFor="let sub of item.sub; let j = index;">
<i style="color: white" class={{item.sub[j].class}}></i>{{item.sub[j].name}}
<ul *ngFor="let smn of sub.submenu; let x = index;">
<li>{{smn.name}}</li>
</ul>
</li>
</ul>
</li>
heres the JSON i've used:
{
"menu": [
{
"name": "Menu Name",
"link": "link",
"class": "icon-ambientais fs1 icon menu-button",
"sub": [{
"name": "SubMenuTitle1",
"link": "link",
"class": "icon-ambientais fs1",
"submenu":[{
"name": "SubMenu1",
"routerlink": "/link/Qld"
},{
"name": "SubMenu2",
"routerlink": "/link/eQld"
},{
"name": "SubMenu3",
"routerlink": "/link/aQld"
}
]
},
{
"name": "SubMenuTitle2",
"link": "link",
"class": "icon-gestao-ambient fs1",
"submenu":[{
"name": "SubMenu1",
"routerlink": "/link2/oQld"
},{
"name": "SubMenu2",
"routerlink": "/doc/eQld"
}
]
}
]
}
}
Hope that helps somebody on the futurue

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

Getting data from JSON ( AngularJS)

I've got the whole questions that I have in my JSON file, but I need only one until the user will click the right answer and go to the next one
HTML template:
<div ng-controller="quizController">
<ul>
<li ng-repeat="q in allData">
<h1 id="question">{{q.question}}</h1>
</li>
</ul>
<div class="answers">
<a class="btn btn-primary"><p>New York</p></a>
<a class="btn btn-warning"><p>Miami</p></a>
<a class="btn btn-success"><p>Washington</p></a>
<a class="btn btn-danger"><p>LA</p></a>
</div>
JS:
app.controller("quizController", function($scope, $http){
$http.get("questions.json")
.then(function(response){
$scope.allData = response.data;
});
});
JSON file:
[
{
"question": "Which is the largest country in the world by population?",
"options": ["India", "USA", "China", "Russia"],
"answer": 2
},
{
"question": "When did the second world war end?",
"options": ["1945", "1939", "1944", "1942"],
"answer": 0
},
{
"question": "Which was the first country to issue paper currency?",
"options": ["USA", "France", "Italy", "China"],
"answer": 3
},
{
"question": "Which city hosted the 1996 Summer Olympics?",
"options": ["Atlanta", "Sydney", "Athens", "Beijing"],
"answer": 0
}
]
You should not use ng-repeat then, since this will just loop through your questions and show them all at once in the UI.
Instead, store your questions array in another variable and then bind your UI to a specific index of that variable.
app.controller("quizController", function($scope, $http){
$scope.allData = [];
//Initially set to first element (question), then you will need to increment in further logic elsewhere probably on a button click handler if the answer is correct
$scope.currentQuestion = $scope.allData[0];
$http.get("questions.json")
.then(function(response){
$scope.allData = response.data;
});
});
This is similar to mindparses approach but goes a little deeper. You can navigate back and forth. It's not full proof but should help you on your way.
HTML
<div ng-app="app" ng-controller="quizController">
<div ng-app="app" ng-controller="quizController">
<p>
<h1 id="question">{{currentQ.question}}</h1>
<div class="answers">
<ul ng-repeat="option in currentQ.options">
<li>{{option}}</li>
</ul>
</div>
</p>
<button ng-click="move(-1)">Previous</button>
<button ng-click="move(1)">Next</button>
</div>
</div>
JS/CONTROLLER
var app = angular.module('app', []);
app.controller("quizController", function ($scope) {
$scope.move = function (direction) {
// you're gonna need an IF block here to stop it from going out of range.
var position = $scope.allData.indexOf($scope.currentQ);
$scope.currentQ = $scope.allData[position + direction];
}
$http.get("questions.json").then(function(response){
$scope.allData = response.data;
$scope.currentQ = $scope.allData[0];
});
});
JSFIDDLE

Loop over JSON with Handlebars JS and Ember JS

I am learning Ember JS and Handlebars JS so I am very new to this. I am having an issue trying to loop through the following JSON.
Here is my JSON:
{
"sgt_rules": {
"app_tags": {},
"city": [],
"consumer_tags": [],
"device_tags": {
"os": [
"ios"
]
},
"participation": null,
"registration": null
}
}
This is my handlebars template:
<h2>{{controllers.segment.sgt_name}}</h2>
<script type="text/x-handlebars" data-template-name="pull">
<ul>
<li>{{getsegmentrules}}</li>
</ul>
</script>
The ember helper function in case I need to modify it:
import Ember from 'ember';
var controller = Ember.Controller.extend({
needs: ['segment'],
getsegmentrules: function () {
var model = this.get('content').get('sgt_rules');
}.property()});
export default controller;
I have tried this but it doesn't work:
<script type="text/x-handlebars" data-template-name="pull">
<ul>
<li>{{controllers.segment.sgt_rules}}</li>
{{#each segment in controllers.segment.sgt_rules}}
<li>App Tags: {{segment.app_tags}} <br /> City: {{segment.city}} <br />
Consumer Tags: {{segment.consumer_tags}} <br /> Device Tags: {{segment.device_tags}} <br />
Participation: {{segment.participation}} <br /> Registration: {{segment.registration}} <br />
<ul>
{{#each obj in segment.device_tags}}
<li>{{obj.os}}</li>
{{/each}}
</ul>
</li>
{{/each}}
</ul>
</script>
What am I missing here? Do I need to write any helper function as well?
shouldn't you return a value here?
getsegmentrules: function () {
var model = this.get('content').get('sgt_rules');
return model;
}.property()});
Also where are you setting the JSON data?

Hash tag links in #each loop with Handlebars and Ember

I have an array of objects:
objects = [
{
name: "a",
val: 1
},
{
name: "b",
val: 2
}
]
I'm trying to produce the following HTML with Handlebars:
<ul>
<li> ... </li>
<li> ... </li>
</ul>
If I didn't need the hash, I would do it like this:
<ul>
{{#objects}}
<li> <a {{bindAttr href="name"}}>...</a> </li>
{{/objects}}
</ul>
I can't use href="#name" or href=#"name". Is there a way to get the hash in front of the name property?
<ul>
{{#each item in objects}}
<li> ... </li>
{{/each}}
</ul>
But i'm not sure what you're doing, you probably want to use the link-to helper