Can't bind 2 objects from JSON in Angularjs? - javascript

I'm new to Angularjs. I am learning about factory.
In my example, I have 2 requests to Restful Api and got 2 responses in JSON format.
With the first json, I can use ng-repeat to show them but the 2nd json can't bind to the view.
How can I bind both responses into the same view?
this is my code
index.html file
<!DOCTYPE html>
<html lang="en" ng-app='f1feed'>
<head>
<title>AngularJS Routing example</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
<style>
body {
padding-top: 10px;
background-color: #F5F5F5;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="DriverController">
<table>
<thead>
<tr>
<th colspan="4">Drivers Champion Standings</th>
</tr>
<tr>
<th>No.</th>
<th>Full name</th>
<th>Driver ID</th>
<th>Points</th>
</tr>
</thead>
<tbody ng-repeat="driver in drivers">
<tr>
<td>{{$index + 1}} </td>
<td>{{driver.Driver.givenName}} {{driver.Driver.familyName}}</td>
<td>{{driver.Driver.driverId}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
<div class="info">
<h1>1st Driver Detail info</h1>
<ul>
<li>Driver ID: {{alonso.driverId}} </li>
<li>Date of Birth: {{alonso.dateOfBirth}} </li>
<li>Nationality: {{alonso.nationality}}</li>
</ul>
</div>
</body>
</html>
file app.js
var app = angular.module('f1feed',[]);
app.factory('DriverSev', function($http){
var driverApi = {};
driverApi.getDriverStands = function(){
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/current/driverStandings.json?callback=JSON_CALLBACK'
});
};
driverApi.getDetail = function(){
return $http({
method: 'JSONP',
url: 'http://ergast.com/api/f1/drivers/alonso.json?callback=JSON_CALLBACK'
});
};
return driverApi;
});
app.controller('DriverController', function DriverController($scope, DriverSev){
$scope.drivers = [];
$scope.alonso = [];
DriverSev.getDriverStands().success(function(data){
$scope.drivers = data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
})
DriverSev.getDetail().success(function(data){
$scope.alonso = data.MRData.DriverTable.Drivers;
console.log($scope.alonso);
})
});
Thanks

your $scope.alonso is unused in your view put it in another ng-repeat to display it
<table>
<thead>
<tr>
<th colspan="4">Drivers Champion Standings</th>
</tr>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody ng-repeat="alon in alonso">
<tr>
<td>{{$index + 1}} </td>
<td>{{alon}}</td>
</tr>
</tbody>
</table>
if it's the same data model, push it in $scope.drivers

$scope.alonso is an array.
<ANY ng-repeat="details in alonso">
<any>Driver ID: {{details.driverId}} </any>
<any>Date of Birth: {{details.dateOfBirth}} </any>
<any>Nationality: {{details.nationality}}</any>
</ANY>
should do the trick, or something ugly such as {{alonso[0].driverId}}

Related

Combining objects arrays, then displaying them for relevant people

I have many objects that I want to combine, and then display only the ones which have a matching ID to another object.
So for instance; when a user clicks on John, it would display the fishing trips that john went on (there is are matching IDs in the User Info Object and the Fishing Trip Object).
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="lib/style.css" />
<script src="lib/script.js"></script>
</head>
<body ng-app="plunker" ng-cloak>
<div ng-controller="MainCtrl">
<h1>Select relevant information from a list</h1><br>
<table>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
<tr ng-repeat = "x in userInfo">
<td>{{x.name}}</td>
<td>{{x.ID}}</td>
<td><button ng-click = "viewMore()">View More</button></td>
</tr>
</table><br><br>
<div ng-show = "showDiv">
<table><h3>Selected Information</h3>
<tr>
<th>Name (Selection)</th>
<th>Hobby (Selection)</th>
<th>ID (Selection)</th>
</tr>
<tr ng-repeat = "x in userInfo">
<td>{{x.name}}</td>
<td>{{x.hobby}}</td>
<td>{{x.ID}}</td>
</tr>
</table><br><br>
<div>
<h3>Fishing Trips for selected person:</h3>
{{fishingTrip1}} {{fishingTrip2}}
</div>
</div>
</div>
</body>
</html>
import angular from 'angular';
angular.module('plunker', []).controller('MainCtrl', function($scope) {
$scope.userInfo = [{"name":"John", "hobby":"fishing", "ID":"123"},
{"name":"Bob", "hobby":"Golf", "ID":"199"},
{"name":"Jerry", "hobby":"Football", "ID":"aAAa"}];
$scope.fishingTrip1 = [{"location":"Alaska", "fisherman":"John", "ID":"123"},
{"location":"Alaska", "fisherman":"Bob", "ID":"144"},
{"location":"Alaska", "fisherman":"Alex", "ID":"161"}];
$scope.fishingTrip2 = [{"location":"Colorado", "fisherman":"Sammy", "ID":"111"},
{"location":"Colorado", "fisherman":"John", "ID":"123"},
{"location":"Colorado", "fisherman":"Jerry", "ID":"aAAa"}];
$scope.selectedID = null;
$scope.viewMore = function(ID){
$scope.showDiv = true;
$scope.selectedID = ID;
};
});
https://plnkr.co/edit/M8X51cmtMmTNNf2S?open=lib%2Fscript.js&deferRun=1
<html>
<head>
<link rel="stylesheet" href="lib/style.css" />
<script src="lib/script.js"></script>
</head>
<body ng-app="plunker" ng-cloak>
<div ng-controller="MainCtrl">
<h1>Select relevant information from a list</h1><br>
<table>
<tr>
<th>Name</th>
<th>ID</th>
</tr>
<tr ng-repeat = "x in userInfo">
<td>{{x.name}}</td>
<td>{{x.ID}}</td>
<td><button ng-click = "viewMore(x)">View More</button></td>
</tr>
</table><br><br>
<div ng-show = "showDiv">
<table><h3>Selected Information</h3>
<tr>
<th>Name (Selection)</th>
<th>Hobby (Selection)</th>
<th>ID (Selection)</th>
</tr>
<tr ng-repeat = "x in userInfo">
<td>{{x.name}}</td>
<td>{{x.hobby}}</td>
<td>{{x.ID}}</td>
</tr>
</table><br><br>
<div>
<h3>Fishing Trips for selected person:</h3>
<ul>
<li ng-repeat="trip in fishingTripsToShow">{{trip.location}}</li>
</div>
</div>
</div>
</body>
</html>
And in your js file
import angular from 'angular';
angular.module('plunker', []).controller('MainCtrl', function($scope) {
$scope.userInfo = [{"name":"John", "hobby":"fishing", "ID":"123"},
{"name":"Bob", "hobby":"Golf", "ID":"199"},
{"name":"Jerry", "hobby":"Football", "ID":"aAAa"}];
$scope.fishingTrip1 = [{"location":"Alaska", "fisherman":"John", "ID":"123"},
{"location":"Alaska", "fisherman":"Bob", "ID":"144"},
{"location":"Alaska", "fisherman":"Alex", "ID":"161"}];
$scope.fishingTrip2 = [{"location":"Colorado", "fisherman":"Sammy", "ID":"111"},
{"location":"Colorado", "fisherman":"John", "ID":"123"},
{"location":"Colorado", "fisherman":"Jerry", "ID":"aAAa"}];
$scope.fishingTripsToShow = [];
$scope.selectedFisherman = null;
$scope.viewMore = function(selectedFisherman){
$scope.showDiv = true;
$scope.selectedFisherman = selectedFisherman;
$scope.fishingTripsToShow = [];
$scope.fishingTrip1.forEach(function(f){
if(f.fisherman == $scope.selectedFisherman.name){
$scope.fishingTripsToShow.push(f);
}
});
$scope.fishingTrip2.forEach(function(f){
if(f.fisherman == $scope.selectedFisherman.name){
$scope.fishingTripsToShow.push(f);
}
});
console.log($scope.fishingTripsToShow);
};
});

cant generate the PDF(with all details) using html-pdf in NodeJS

I am a bit stuck when creating the PDF from the html template. if i use the static entries it does work but i am looking to generate the pdf for multiple items and the items can vary each time, i am not sure if i am missing something any suggestion guys please.
after i added .map function in the pdfTemplate.js file as below to go through each object and get the price, it seems to not working properly
snippet from the main ./documents/pdfTemplate Js file
customer_dataand_Itemsbought.map((eachitem) => {
total = total + eachitem.price;
return ` <tr class="heading">
<td>Bought items:</td>
<td>Price</td>
</tr>
<tr class="item">
<td>First item:</td>
<td>${eachitem.price}$</td>
</tr>
<tr class="item">
<td>Second item:</td>
<td>${eachitem.price}$</td>
</tr>`;
})`
Note: PDF is still generating but missing every bit that i included after the .map function
main ./documents/pdfTemplateJs file
module.exports = (customer_dataand_Itemsbought) => {
//customer_dataand_Itemsbought is array of objects[obj[0],obj[1],...] and at obj[0] is the customer details object and after that each index object contains the customer bought items detail/price
let customer_Name = customer_dataand_Itemsbought[0].user_FirstName;
let receipt_Id = customer_dataand_Itemsbought[0].Invoice_No_latest;
let total_Price;
customer_dataand_Itemsbought.shift();
const today = new Date();
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PDF Result Template</title>
<style>
........
</style>
</head>
<body>
<div class="invoice-box">
<table cellpadding="0" cellspacing="0">
<tr class="top">
<td colspan="2">
<table>
<tr>
<td class="title"><img src="https://i2.wp.com/cleverlogos.co/wp-content/uploads/2018/05/reciepthound_1.jpg?fit=800%2C600&ssl=1"
style="width:100%; max-width:156px;"></td>
<td>
Datum: ${`${today.getDate()}. ${today.getMonth() + 1}. ${today.getFullYear()}.`}
</td>
</tr>
</table>
</td>
</tr>
<tr class="information">
<td colspan="2">
<table>
<tr>
<td>
Customer name: ${customer_Name} // this still appears on the PDF
</td>
<td>
Receipt number: ${receipt_Id} // this still appears on the PDF
</td>
</tr>
</table>
</td>
</tr>`;
// here i used the .map function to go through each array object. nothing appears from here onwards on the pdf
customer_dataand_Itemsbought.map((eachitem) => {
total = total + eachitem.price;
return ` <tr class="heading">
<td>Bought items:</td>
<td>Price</td>
</tr>
<tr class="item">
<td>First item:</td>
<td>${eachitem.price}$</td>
</tr>
<tr class="item">
<td>Second item:</td>
<td>${eachitem.price}$</td>
</tr>`;
})`
</table>
<br />
<h1 class="justify-center">Total price: ${total_Price}£</h1>
</div>
</body>
</html>
`;
};
at server.js side
const pdf = require("html-pdf");
const pdfTemplate = require("./documents/pdfTemplate");
pdf.create(pdfTemplate(customer_dataand_Itemsbought), {}).toFile("./filename.pdf", function (err, res) {
if (err) {
console.log(err);
}
});
When you have enclosed map function's body in curly braces - meaning you have multiple statements for processing data, you are expected to return from it explicitly:
customer_dataand_Itemsbought.map((eachitem) => {
total = total + eachitem.price;
return `<tr class="heading">
<td>Bought items:</td>
<td>Price</td>
</tr>
<tr class="item">
<td>First item:</td>
<td>${eachitem.price}$</td>
</tr>
<tr class="item">
<td>Second item:</td>
<td>${eachitem.price}$</td>
</tr>`;
})

Angular JS Display Response Values

I'm trying to display data from one page to another in Angular JS. Using displayResponse in Firefoxes Console, the Response data seems to be retrieved however I'm having trouble trying to display the values on the page which is troublesome since a Team member was able to get them to display properly on other pages on the site.
Here is the Code so far (I have removed chucks of the script to save screen space. These bits of code are not relevant to the issue afaik):
var app = angular.module("myApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/ViewSalesRecords', {
templateUrl: 'view-sales-records.html',
controller: 'salesRecordController'
}).
when('/ViewSingleSale', {
templateUrl: 'view-single-sale.html',
controller: 'salesRecordController'
});
});
app.controller('salesRecordController', ['$scope', '$http', function($scope, $http) {
$scope.displaySingleSale = function(sale_id) {
$http.post('read_sale.php', {
'sale_id': sale_id
})
.then(function(response) {
$scope.singleSalesRecord = response.data;
console.log($scope.singleSalesRecord);
})
}
$http.get("read_sale.php")
.then(
function(response) {
$scope.salesRecords = response.data;
}
)
}]);
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<table class="table table-hover" data-ng-model="sale_id">
<p><strong>Sale ID: {{displayResponse}} </strong> </p>
<p><strong>Sale Date: </strong> </p>
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Item Total</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in singleSalesRecord">
<td>{{s.product_id}}</td>
<td>{{s.product_name}}</td>
<td>{{s.quantity}}</td>
<td>${{s.product_price}}</td>
</tr>
</tbody>
</table>
<p><strong>Total: ${{s.orderTotal}}</strong></p>
The page that is sending the data
<head>
<link href="./styles/style.css" rel="stylesheet">
</head>
<div>
<input class="form-control searchBar" data-ng-model="searchText.sale_id" type="text" placeholder="Search sales by Sale ID">
<table class="table table-hover">
<thead>
<tr>
<th>Sale ID</th>
<th>Total items</th>
<th>Total price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="s in salesRecords | filter:searchText:strict">
<td>{{s.sale_id}}</td>
<td>{{s.TotalItems}}</td>
<td>${{s.orderTotal}}</td>
<td>
<button class="btn btn-primary">View</button>
<button class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
So wall of text taken into consideration, what am I doing wrong? I will admit I'm not too familiar with AngularJS so this might be a very amateur mistake on my part.
I figured out that the problem was that the values that I wanted to transfer were been wiped when I moved to another page. So I decided to simply display them on the first page instead hyperlinking to another.

How to change the key name for each element in array using ng-repeat

I have an array of object, which I am showing in table through ng-repeat.
<table>
<thead>
<tr>
<th ng-repeat="col in columnHeaders">{{col}}</th> //['Name', 'Bank Name','Code', 'Type','Status'];
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data track by $index">
<td ng-repeat="col in columnRows">{{row[col]}}</td> //['name', 'bankName','code', 'type','isActive'];
</tr>
</tbody>
</table>
I am using ng-repeat in <th></th> and <td></td> too. But my columnHeaders name and row property(columnRows) names are different. I want to change my property name to same as column header name while using ng-repeat on <td></td> tag.
I am thought of using alias 'as' but not sure how to use it for each element.
Can anyone help me?
Instead of using two columnRows and header rows(array of string) , make a single array of keyHash(column data key and header string )
check running fiddle for this
and code be like :-
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<thead>
<tr>
<th ng-repeat="col in columnRows">{{col.displayStr}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in data track by $index">
<td ng-repeat="col in columnRows">{{row[col.key]}}</td>
</tr>
</tbody>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.columnRows = [
{key:'name',displayStr:'Name'},
{key:'bankName',displayStr:'Bank Name'},
{key:'code',displayStr:'Code'},
{key:'type',displayStr:'Type'},
{key:'isActive',displayStr:'Status'}
]
$scope.data = [
{
name:'James',
bankName:'RBL',
code:'1234',
type:'Saving',
isActive:true
},
{
name:'Riyan',
bankName:'DSB',
code:'1234',
type:'Current',
isActive:true
}
];
});
</script>
</body>
</html>

Reversing first and last names using jquery

Trying to take this table and take the names, when I click one radio button it changes the names from something like: Tom Hanks to Hanks, Tom. Here is the html:
<h1>Address Book</h1>
Show Names as:
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbod
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Interview Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise</td>
</tr>
</tbody>
</table>
</div>
Here is the jquery, its all I could come up with and does not work at all. :(
$(document).ready(function () {
$("input[name='change_last_first']").click(function () {
$(".name").text(function() {
$(this).split(" ").reverse();
});
});
});
});
You need to return the result. Also since you are using the function arg syntax of text use the second argument of the function for the current text.
$(".name").text(function(_, cur) {
return curText.split(/\s+|,/).reverse();
});
Fiddle
Another easy way to handle this assuming the general format of name is First Last or Last, First:
$("input[name='change_last_first']").change(function () {
var arr = [" ", ","],
sep = this.value === 'first' ? 0 : 1;
$(".name").text(function (_, curText) {
return curText.split(arr[sep % 2]).reverse().join(arr[(sep + 1) % 2]);
});
});
Demo
For this you need to split full name with space and than you can use reverse().
Note: because reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string.
$("input[name='change_last_first']").click(function () {
$(".name").each(function() {
var revName = $(this).text().split(" ").reverse().join(" ");
$(this).text(revName);
});
});
Try This

Categories

Resources