How to display my JSON datas expressjs/angularjs - angularjs

I am a beginner in JSON.
I would like to display all my JSON datas in my html <div>, but I am not sure how to do it with an object using EXPRESSJS.
Find bellow my JSON Datas
app.post("/form",function(req,res)
{
var departure=req.body.departure;
var destination=req.body.destination;
response = {
"flights": [{
"departure": departure,
"destination": destination,
"time": {
departure: 10,
destination: 12
},
"price": 2000
}, {
"departure": departure,
"destination": destination,
"time": {
departure: 12,
destination: 14
},
"price": 4000
}, {
"departure": departure,
"destination": destination,
"time": {
departure: 14,
destination: 16
},
"price": 8000
}]
};
res.json({departure: departure, destination: destination});
});
My html
<div ng-repeat="item in response">
<dir>{{item.departure}}</dir>
<dir>{{item.destination}}</dir>
<dir>{{item.time.departure}}</dir>
<dir>{{item.time.destination}}</dir>
<dir>{{item.price}}</dir>
</div>
AngularJS code
app.controller('formController', function($scope, $http) {
$scope.pageClass = 'form';
$scope.departure = '';
$scope.destination = '';
$scope.submit = function() {
$http.post('/form', {
departure: $scope.departure,
destination: $scope.destination
}).then(function(res) {
$scope.response = res.data;
});
}
});
At the moment it is displaying only my departure and destination as I asked. Is there a way to display all my datas by writing my res.json() without doing it variable by variable ? I guess I have to do something with ng-repeat as well ?
Thank you by advance

Yes, you need use ng-repeat
var app = angular.module('app',[]);
app.controller('myController',function($scope){
$scope.response = {
"flights": [{
"departure": "departure1",
"destination": "destination1",
"time": {
departure: 10,
destination: 12
},
"price": 2000
}, {
"departure": "departure2",
"destination": "destination2",
"time": {
departure: 12,
destination: 14
},
"price": 4000
}, {
"departure": "departure3",
"destination": "destination3",
"time": {
departure: 14,
destination: 16
},
"price": 8000
}]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="myController">
<div ng-repeat="item in response.flights">
<dir>{{item.departure}}</dir>
<dir>{{item.destination}}</dir>
<dir>{{iteme.time.departure}}</dir>
<dir>{{item.time.destination}}</dir>
<dir>{{item.price}}</dir>
</div>
</div>
</div>
check the docu: https://docs.angularjs.org/api/ng/directive/ngRepeat

you do need to use a ng-repeat
<div ng-repeat="flight in response.flights">
<dir>{{flight.departure}}</dir>
<dir>{{flight.destination}}</dir>
<dir>{{flight.time.departure}}</dir>
<dir>{{flight.time.destination}}</dir>
<dir>{{flight.price}}</dir>
</div>
Reference for ngRepeat
A good reference for anything Angular can be found on the documentation site for AngularJS

Related

AngularJS Filed nested array of objects with array of objects

I'm trying to filter a nested array of objects with my own objects, by idSubject. But I'm not getting the right result.
I have articles (which have subjects)
And a array of objects (which are the subjects I want to filter the articles with)
Data looks like this:
So I'm trying to filter the array of articles by its subjects.
I tried the following:
<div class="panel panel-default"
ng-repeat="searchArticle in searchArticles | filter: {subjects: filterSubjects} as articleSearchResult">
So filterSubjects is the second screenshot and SearchArticles is the first screenshot.
Without much luck.
Hope you can help, please tell me if things are still unclear.
This custom filter will help you.
Example : http://plnkr.co/edit/jMizCLxPH6DtDA5wL15Q?p=preview
HTML:
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<h2>Select Subjects</h2>
<div ng-repeat="subject in subjects">
<label>
<input type="checkbox" ng-model="filterSubjects[subject.id]" ng-true-value="'{{subject.id}}'" ng-false-value="''">{{subject.name}}</label>
</div>
<h2>Filtered Articles</h2>
<div ng-repeat="searchArticle in searchArticles | subjectFilter:filterSubjects">{{searchArticle.name}}</div>
</div>
</body>
JS:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
filtered = articles.filter(function(e){return filterSubjects.indexOf(e.sid) >= 0},filterSubjects);
return filtered;
}
});
if you want to filter based on object :
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.searchArticles = [{
"name": "Article1",
"sid": "1"
}, {
"name": "Article2",
"sid": "1"
}, {
"name": "Article3",
"sid": "2"
}];
$scope.subjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject2",
"id": "2"
}];
$scope.filterSubjects = [{
"name": "Subject1",
"id": "1"
}, {
"name": "Subject1",
"id": "2"
}];
});
app.filter('subjectFilter', function() {
return function(articles, filterSubjects) {
var sFiltered = [];
for (var i = 0; i < filterSubjects.length; i++) {
sFiltered.push(filterSubjects[i].id);
}
var filtered = articles.filter(function(e) {
return sFiltered.indexOf(e.sid) >= 0;
}, sFiltered);
return filtered;
}
});

Updating angularjs controller with websocket data

I'm trying to update my angularjs controller after receiving new information from a websocket server. I am using angular-websockets to create the connection with the websocket server.
Here is my code:
angular.module('VotingApp', ['ngWebSocket'])
.factory('MyVotingResults', function ($websocket) {
// Open a WebSocket connection
var ws = $websocket('ws://localhost:80/test');
//defaults
var collection = {
Question: "This is my question?",
Results: [
{ Percentage: 0, Picture: "http://www.kvmechelen.be/wp-content/uploads/2015/02/De-Witte.jpg", Player: "Seth De Witte", Number: "4", Position: "Defender", Winner: true },
{ Percentage: 0, Picture: "http://www.kvmechelen.be/wp-content/uploads/2016/02/15-16grpsf-037-19715104962_19124904603_o.jpg", Player: "Tim Matthys", Number: "7", Position: "Midfielder", Winner: false },
{ Percentage: 0, Picture: "http://www.kvmechelen.be/wp-content/uploads/2016/02/NICOLAS-VERDIER.jpg", Player: "Nicolas Verdier", Number: "99", Position: "Forward", Winner: false }
]
};
ws.onOpen(function () {
console.log("connectie is open");
ws.send("Hello world!");
});
ws.onClose(function () {
console.log("connectie is closed");
});
ws.onError(function () {
console.log("error!");
});
ws.onMessage(function (response) {
console.log("received an update: ", response);
collection = JSON.parse(response.data);
});
return {
collection: collection,
get: function () {
ws.send(JSON.stringify({ action: 'get' }));
}
};
})
.controller('VotingController', function ($scope, MyVotingResults) {
$scope.Data = MyVotingResults.collection;
})
I am initializing my collection variable with some data to begin. That works and it is shown on the page like it is supposed to.
Here is my html:
<div class="content" ng-controller="VotingController">
<div class="vraag">
<p>{{Data.Question}}</p>
</div>
<div class="antwoorden">
<div class="antw" ng-repeat="result in Data.Results">
<div class="result">
<div class="resultWinner">
<img src="img/winner.png" />
</div>
<div class="resultImage">
<img src="{{result.Picture}}" />
</div>
<div class="resultBalk">
<p><span class="timer">{{result.Percentage}}</span>%</p>
</div>
</div>
<div class="antwText">
<p><span>{{result.Number}}.</span> {{result.Player}}</p>
<p>{{result.Position}}</p>
</div>
</div>
</div>
</div>
My websocketserver is a simple testserver that sends back this json:
{
"Question": "Who deserves the Man of the Match award?",
"Results": [{
"Percentage": 25.0,
"Picture": "http://www.kvmechelen.be/wp-content/uploads/2015/02/De-Witte.jpg",
"Player": "Seth De Witte",
"Number": "4",
"Position": "Defender",
"Winner": false
}, {
"Percentage": 40.0,
"Picture": "http://www.kvmechelen.be/wp-content/uploads/2016/02/15-16grpsf-037-19715104962_19124904603_o.jpg",
"Player": "Tim Matthys",
"Number": "7",
"Position": "Midfielder",
"Winner": true
}, {
"Percentage": 35.0,
"Picture": "http://www.kvmechelen.be/wp-content/uploads/2016/02/NICOLAS-VERDIER.jpg",
"Player": "Nicolas Verdier",
"Number": "99",
"Position": "Forward",
"Winner": false
}]
}
Why won't page update? I based my code on this example:
https://angularclass.github.io/angular-websocket/
Any help is appreciated.
EDIT:
I changed my controller to this but it still doesn't work unfortunately.
.controller('VotingController', function ($scope, MyVotingResults) {
$scope.Data = MyVotingResults.collection;
$scope.$watch(function () {
return MyVotingResults.collection;
}, function (newValue) {
$scope.Data = newValue;
});
})
You can "watch" that service variable in your controller and update the scope accordingly:
$scope.$watch(function () {
return MyVotingResults.collection;
}, function (newValue) {
$scope.Data = newValue;
});

angular.forEach() not working

Hi friend I'm beginner in angular and getting stuck by using angular.forEach() function. I just want to call data from a nested array in data.json file. Please check my code below... ****I want to call data from --users-- key****
HTML
<div class="user-container" ng-controller="users">
<ul class="list">
<li ng-repeat="(key, value) in items">
{{key}} <p> {{value}}
</li>
</ul>
</div>
Problems with current code
When run my code in browser Its giving me only 2 <li> in ng-repeat then in {{Key}} I'm getting 0 in first <li> and 1 in second <li>
and in {{value}} I'm getting whole user list in first <li> and in second <li> their is no data
data.json
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
Controller.js
var myApp = angular.module('app', []);
myApp.service('userData', ['$http', function($http){
return{
userslist : function(){
return $http({'url' : 'data.json', 'method' : 'GET'}).then(function(response){
return response.data;
}, function(data){
console.log(data)
})
}
}
}]);
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data, function(item){
//console.log(item.users);
$scope.items.push(item.users)
})
console.log($scope.items)
})
}]);
response is the HTTP response, with its body (data), headers, etc.
So response.data is the body, which looks like this:
{
"data": {
"new": true,
"show_page": false,
"status": "signedin",
"users": [{
"Michele": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
"Gerry": {
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
}]
},
"success": true
}
What you want is to access the users field of the data field of this body. So what you want is
userData.userslist().then(function(data){
$scope.items = data.data.users;
console.log($scope.items)
})
$scope. items is an array, not an object. You want to display the elements of this array. So the syntax is:
{{ user }}
Your JSON is awful, because each user is an object with a single field, and you have no way of knowing the name of that field. You'd better change it to
"users": [
{
"name": "Michele",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
},
{
"name": "Gerry",
"logo": "xyz.jpg",
"status": "active",
"active_since": 2015,
"order": 1
}
]
That way you could just do:
<li ng-repeat="user in items">
{{ user.name }}, active since {{ user.active_since }}.
use this
myApp.controller('users', ['$scope', '$http', 'userData', function($scope, $http, userData){
userData.userslist().then(function(data){
//var provideDataKey = Object.keys(data.users)[0];
$scope.items = [];
angular.forEach(data.users[0], function(item){
$scope.items.push(item);
})
console.log($scope.items)
})
}]);
you were iterating over data and not on users.

Reading nested json in Angularjs

I am newbie to AngularJS. I have JSON file which I have to fetch using angularjs!
JSON File
{
"records": [
{
"students": [
{
"id": 1,
"name": "Bill",
},
{
"id": 2,
"name": "Steve",
}
],
"exstudent": [
{
"id": 1,
"name": "Woz",
},
{
"id": 2,
"name": "Jonathan",
}
]
}
]
}
Controller part snippet -
$http.get('json/somedata.json').success(function (data){
$scope.name = data.records.student.name;
$scope.exname = data.records.exstudent.name;
});
}])
HTML
<div class="panel-body" ng-repeat = "browse in name">
{{browse.student.name}}
</div>
Which part I am doing wrong? I think the problem is with ng-repeat!
Need Help
You can't use data.records.students.name as students is an Array.
You can however store its data into your $scope and use it in the ng-repeat:
$http.get('json/config.json').success(function (data){
$scope.students = data.records.students;
$scope.exstudents = data.records.exstudent;
});
Then in your HTML use the ng-repeat like this:
<div class="panel-body" ng-repeat="student in students">
{{student.name}}
</div>

Backbone JS Create dynamic views and collection

I am a bit noob to backbone JS
I have this one code in which I need to list out the categories according to the json and list them out on the page.
Now when user clicks on any of the category list a new JSON attached to that category is fetched from the server and listed on the page.
My problem is I have listed out the categories but don't know how to get new JSON and display it on the screen by creating views and collection for new JSON dynamically depending on thecategory chosen.
Here is my HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Category list</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Category list</h1>
<hr />
<div class='categoryList'></div>
<div class='selected_category'></div>
</div>
<script type="text/template" id="events-template">
<% _.each( CategoryCollection, function(Category){ %>
<div class='category'>
<h2 class='<%= Category.get("category") %>' >
<%= Category.get("category") %>
</h2>
</div>
<% }); %>
</script>
<script type="text/template" id="selectedCategory-template">
<% _.each( SelectedCategoryCollection, function(selected_category){ %>
<div class='category_list'>
<%= selected_category.get("category") %>
</div>
<% }); %>
</script>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
var categoryJSON;
var Category = Backbone.Model.extend();
var CategoryCollection = Backbone.Collection.extend({
model: Category,
url: 'categories.json',
parse: function (response) {
categoryJSON = response;
console.log(categoryJSON)
return response;
}
});
var CategoryAbout = Backbone.View.extend ({
el: '.categoryList',
render: function () {
var that = this;
// console.log(that)
var eventCategory = new CategoryCollection();
// console.log(eventCategory);
eventCategory.fetch({
success: function (CategoryCollection) {
// console.log(CategoryCollection)
var template = _.template($('#events-template').html(), {CategoryCollection: CategoryCollection.models});
// console.log(template)
that.$el.html(template);
}
})
},
events: {
"click .category h2" : "doSearch"
},
doSearch: function(event){
// Button clicked
console.log('clicked');
console.log(event.toElement.className)
router.navigate('/category/'+event.toElement.className, { trigger: true });
// window.location.href = window.location.href + '/#/category/all';
}
});
var CategoryAbout = new CategoryAbout ();
var Router = Backbone.Router.extend({
routes: {
'': 'home',
"category/:categoryName": "getCategory",
}
});
var router = new Router();
// console.log(router)
router.on('route:home', function () {
// console.log(this)
console.log('home');
CategoryAbout.render();
});
router.on('route:getCategory', function (categoryName) {
console.log( "Category Name " + categoryName );
var urlToFetch;
for (var i = 0; i < categoryJSON.length; i++) {
if(categoryJSON[i].category == categoryName)
{
urlToFetch = categoryJSON[i].data;
}
};
console.log(urlToFetch);
});
Backbone.history.start();
</script>
and the JSON file for Category
[
{
"category": "all",
"data": "all.json"
},
{
"category": "music",
"data": "music.json"
},
{
"category": "business",
"data": "business.json"
},
{
"category": "sports",
"data": "sports.json"
},
{
"category": "workshops",
"data": "workshops.json"
}
]
and say that we have chosen workshop category then JSON of workshop is like this
{
"request": {
"venue": "0",
"ids": "0",
"type": "json",
"city": "NY",
"edate": 0,
"page": 0,
"keywords": "0",
"sdate": 0,
"category": "workshops",
"city_display": "NY",
"rows": 50
},
"count": 10,
"item": [
{
"event_id": "230801950442480",
"eventname": "Holiday special YES! course :) :)",
"thumb_url": "http://graph.facebook.com/230801950442480/picture",
"thumb_url_large": "http://graph.facebook.com/230801950442480/picture?type=large",
"start_time": 1395943200,
"start_time_display": "Thu Mar 27 2014 at 06:00 pm",
"end_time": 1396213200,
"end_time_display": "Sun Mar 30 2014 at 09:00 pm",
"location": "NY,ABC street",
"venue": {
"street": "",
"city": "NY",
"state": "XYZ",
"country": "PQR"
},
"label": "Tomorrow",
"featured": 0
},
{
"event_id": "230801950442480",
"eventname": "Holiday special YES! course :) :)",
"thumb_url": "http://graph.facebook.com/230801950442480/picture",
"thumb_url_large": "http://graph.facebook.com/230801950442480/picture?type=large",
"start_time": 1395943200,
"start_time_display": "Thu Mar 27 2014 at 06:00 pm",
"end_time": 1396213200,
"end_time_display": "Sun Mar 30 2014 at 09:00 pm",
"location": "NY,ABC street",
"venue": {
"street": "",
"city": "NY",
"state": "XYZ",
"country": "PQR"
},
"label": "Tomorrow",
"featured": 0
}
]
}
thanks in advance.
let me know if I am missing out any data

Resources