Handlebar helper and .toLocaleString - javascript

I display results of a json in Handlebars including numbers that I'd like to format with .toLocaleString().
My json sample:
[{"id": "1",
"results": [{
"price": 5000
},
{
"price": 6000
}]
},
{"id": "2",
"results": [{
"price": 15000
},
{
"price": 16000
}]
}]...
Then I render it with Express in the backend and Handlebars in front:
{{#each results as |auction|}}
<span class="results__container--price">{{auction.price}} €</span>
{{/each}}
(In reality, it's more complexe)
But I don't know how to use toLocaleString(). Maybe I have to loop through "prices in Express but I don't know how to do it. Is it possible to use it directly with Handlebars ?

Use a helper function
Handlebars.registerHelper('toLocaleString', function(number) {
return number.toLocaleString()
})
var source = document.getElementById("temp").innerHTML;
var template = Handlebars.compile(source);
var context = {
title: "Hello",
count: 123456789
};
var html = template(context);
document.getElementById("out").innerHTML = html;
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.1.2/handlebars.min.js"></script>
<script id="temp" type="text/x-handlebars-template">
<div class="test">
<h1>{{title}}</h1>
<h2>{{toLocaleString count}}
</div>
</script>
<div id="out"></div>

Related

how to select specific json data and store it into an array in Vue Js?

I am facing issue to store category SINGLES related data into an array and then use this array to display show data.Basically, I just want to store data that is only belong to category "SINGLES" from json file that I named it "data.json" into an array.Can anyone help me please. I would really appreciate that.
Index.html
<div id="app">
<div class="col-lg-4 col-sm-6" v-for="model in jsonSingleData">
<div class="beeton-models-box">
<div class="image-holder">
</div>
<div class="text-box">
<h3>{{model.title}}</h3>
<p>{{model.bedrooms}}</p>
</div>
</div>
</div>
</div>
script.js
var vm = new Vue({
el:'#app',
data:{
jsonSingleData:[]
},
created:function(){
this.fetchDataAll();
},
methods:{
fetchDataAll: function(){
var url="data.json";
axios.get(url)
.then(function(res){
res.data.models.forEach(single=>{
if(single.category=='SINGLES')
{
vm.jsonSingleData=single;
console.log(single);
}
});
});
}
The below is my json file.
data.json
{
"models": [
{
"title": "IRIS",
"project": "ABC",
"category": "SINGLES",
"bedrooms": 3
},
{
"title": "LILAC",
"project": "ABC",
"category": "DOUBLE",
"bedrooms": 4
},
{
"title": "ASTER",
"project": "ABC",
"category": "SINGLES",
"bedrooms": 4
}
]
}
Looks like your method is missing some points. Also, you are missing a } at the end.
Try this:
fetchDataAll: function(){
var vm = this;
var url="data.json";
axios.get(url)
.then(function(res){
res.data.models.forEach((single)=>{
if(single.category=='SINGLES')
{
vm.jsonSingleData.push(single);
console.log(single);
}
});
});
}

Angular 1.6 $http.get unable to read from json

I am trying to read the json data from a static json file that I have for testing on a local web server but I cannot get anything to show up with using the $http.get() service. I looked at a few other similar questions here but all accepted answers account for use of the promise methods, however on the angularjs v1.6.x+ these have been depreciated.
Initially I tried setting my json data on a variable inside of the controller, and everything worked fine, however once I moved to a JSON file nothing shows up. My first error was that I was unaware the JSON file has to be in ANSI format for the JSON.parse() angular calls to be able to work. Before switching the file encoding to ANSI I was getting syntax errors and my json structure was correct. (some text editor like Dreamweaver will create JSON files in UTF-8 format).
At this point when I inspect the webpage there are no JS errors on the console whatsoever, however no data shows up at all. Here is what I have:
My events.json
[
{
"day" : "Monday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
},
{
"day" : "Tuesday",
"objective" : "Pipeline",
"sessions" : [
{
"title" : "Leadership Excellence Luncheon",
"start" : "11:30am",
"end" : "1:00pm",
"location": "room A"
},
{
"title" : "Veteran Resume Workshop",
"start" : "1:15pm",
"end" : "2:00pm",
"location": "room B",
"speakers" : [
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/",
},
{
"name": "Jane Doe",
"title" : "VP",
"company": "Lancer",
"headshot" : "http://placehold.it/119x134.jpg",
}
]
}
]
}
}
Here is my app.js
(function() {
var app = angular.module('Agendas',[]);
app.controller('TableController', ['$scope', '$http',
function($scope,$http) {
$scope.title = "test";
$scope.events = [];
$http({
method: 'POST',
url: 'http://localhost/ang/data/events.json',
}).then( function(response) {
$scope.events = response;
});
}]);
})();
Here is my index.html
<!doctype html>
<html>
<head>
.....
</head>
<body>
....
<div id="agenda" class="mainCont container-fluid well" ng-app="Agendas" ng-controller="TableController">
<div id="day" ng-repeat="event in events">
<h1>{{ event.day }} — {{ event.objective }}</h1>
<div id="sess" ng-repeat="session in event.sessions">
<div style="width: 140px; float: left; clear: left;">{{ session.start }} - {{ session.end }}<br><br><em>Location: {{ session.location }}</em></div> <div style="float: left;"><em>{{ session.title }}</em> <br>
<div class="panelist" ng-repeat="speaker in session.speakers"><img ng-src="{{ speaker.headshot }}"><br>
<a ng-href="{{ speaker.bio }}">{{ speaker.name }}</a><br>
{{ speaker.title }} <br>
{{ speaker.company }}</div>
</div>
</div>
<div class="aghr"></div>
</div>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
I noticed that your JSON file contains some errors. It could be related.
The ending tag should be one to close the array. ]instead of }.
The last field of a JSON object should not have a comma. E.g.:
{
"name": "John Doe",
"title": "Analyst",
"company": "Appel",
"headshot" : "http://placehold.it/119x134.jpg",
"bio": "john-doe/", <--- remove comma
}
You can use a website as jsonlint to validate your JSON.
** As suggested, you might have to clear the browser cache first.
** Additionally change
$scope.events = response;
to
$scope.events = response.data;

interate through nested json file using ng-repeat not working

So I have a json file with nested elements. This is my json file:
[
{
"qid": "1",
"contester": "0",
"answer": "0",
"question": "What are you most likely to do after getting into an argument? ",
"images": [
{
"qid": "1",
"imageid": "AB100",
"imgname": "doghug_q1",
"imgpath": "Images\/Q1\/doghug_q1.jpg"
},
{
"qid": "1",
"imageid": "AB101",
"imgname": "eq_q1.jpg",
"imgpath": "Images\/Q1\/eat_q1.jpg"
},
{
"qid": "1",
"imageid": "AB102",
"imgname": "headache_q1",
"imgpath": "Images\/Q1\/headache_q1.jpg"
},
{
"qid": "1",
"imageid": "AB106",
"imgname": "scream_q1.jpg",
"imgpath": "Images\/Q1\/scream_q1.jpg"
},
{
"qid": "1",
"imageid": "AB107",
"imgname": "shopping_q1",
"imgpath": "Images\/Q1\/shopping_q1.jpg"
},
{
"qid": "1",
"imageid": "AB108",
"imgname": "walkAlone_q1",
"imgpath": "Images\/Q1\/walkAlone_q1.jpg"
}
]
},
{
"qid": "2",
"contester": "0",
"answer": "0",
"question": "Which game would you rather play?",
"images": [
{
"qid": "2",
"imageid": "AB105",
"imgname": "charades_q2.jpg",
"imgpath": "Images\/Q2\/charades_q2.jpg"
},
{
"qid": "2",
"imageid": "AB109",
"imgname": "playingCards_q2.jpg",
"imgpath": "Images\/Q2\/playingCards_q2.jpg"
},
{
"qid": "2",
"imageid": "AB110",
"imgname": "chess_q2",
"imgpath": "Images\/Q2\/chess_q2.jpg"
},
{
"qid": "2",
"imageid": "AB111",
"imgname": "twister_q2",
"imgpath": "Images\/Q2\/twister_q2.jpg"
}
]
}
]
And this is my controller that i used to access the json :
var app= angular.module('myApp', []);
app.controller('ListCtrl', ['$scope', '$http',
function($scope, $http) {
$http.get('results.json').success(function(data) {
$scope.questions = data; // get data from json
angular.forEach($scope.questions, function(item){
console.log(item.images);
})
});
});
}
]);
And then my html code to display the questions and each questions list of images using the ng-repeat :
<body ng-app="myApp" >
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="question in questions"> {{question.qid}} </li>
</ul>
</div>
</body>
As of now iam trying to display the questions id from the json file as a list however the output im getting is a:
{{question.qid}}
as the output in my html page.. Can someone please help me. I dont know what im doing wrong.
your code has some missing things.
Here is working example of your code
http://plnkr.co/edit/FvD26TYZ9v8TbgUBUzN2?p=preview
firstly,
var app = angular.module('myApp', []); //variable app is missing.
secondly, data you mention has missing closing square brace.
First define app
var app = angular.module('myApp', []);
Then initiate your $scope.questions on your controller like
$scope.questions = [];
Also you might need to parse your data with
$scope.questions = JSON.parse(data);
You haven's define the app so you should change the first line of your code to this and check your closing tags on your js code...:
var app = angular.module('myApp', []);
app.controller('ListCtrl', ['$scope', '$http',
function($scope, $http) {
$scope.questions = [];
$http.get('results.json').success(function(data) {
$scope.questions = data; // get data from json
angular.forEach($scope.questions, function(item){
console.log(item.images);
})
});
}
]);
Complete working code for your case :
HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="ListCtrl">
<ul>
<li ng-repeat="question in questions"> {{question.qid}} </li>
</ul>
</div>
</body>
</html>
JS
var app = angular.module('plunker',[]);
app.controller('ListCtrl',function ($scope,$http) {
$http.get('data.json').success(function(data) {
$scope.questions = data; // get data from json
});
});
Working Plunker
It is working !! Try once !!

Passing Json data from Controller to View in Angular JS to build a table

Trying to get the certain fields to display, ideally in a table (headings, rows & columns). And looking for a best way find fields in a Json feed. I tried using the controller to find the fields then pass that data to the view in the HTML.
Is there something wrong in the controller with respect to the Json? the fields are empty. Seems like nothing is passed from the controller to the view ? This is what I tried:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script>
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
}
};
$scope.elements = $scope.result.data.transactionList.map(function (res) {
var e = {};
e.transTypeId = res.transTypeId;
e.userId = res.userId;
e.storeId = res.storeId;
return e;
});
});
</script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from the JSON feed</h1>
<ul>
<li ng-repeat="e in elements">
{{ e.transTypeId}}: {{ e.userId }}, {{ e.storeId }}
</li>
</ul>
</body>
</html>
You have a extra } in your $scope.result. It should be like:
$scope.result = {
"data": {
"transactionList": [{
"barcode": "52905819992681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "12Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}, {
"barcode": "52905819592681",
"training": 0,
"tranNo": 1,
"userId": "8796093054980",
"retailerId": "defaultRetailer",
"storeId": "23Store",
"deviceId": "afd03463-9ee7-45d4-9d2e-8d64a683f126",
"tillId": "2",
"tranTypeId": "regularSale",
"isTranVoid": 0,
"totalItems": 1,
"merchTotal": 50.0,
"promoTotal": 0.0
}]
}
};
// get rid of this};
Here is working plunkr
Perhaps a }; too many?
Automatic indentation usually makes those kinds of errors apparent.
Have you tried to use ng-model="...", it gives you the opportunity to overwrite an attribute or to show it. You can try it with
<input type="number" ng-model="someID" disabled="disabled">
*disabled if u need readOnly on that field.
and see how it works, maybe it can help you out.
regards
I may be wrong, but you are trying to read json data directly without parsing it?
MDN JSON.parse()
Also it would be nice if you upload your code on something like http://jsfiddle.net
This way people can test it out.

Show only date in AngularJS

I have a JSON array like this one:
[
{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
},
{
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}
]
In a <div> tag I am doing this:
<div> class="row" ng-repeat="item in array"
{{item.createdOn}}
</div>
The output is : 2015-09-01 13:50:59, but I don't want the time part to be shown, i.e. required output is just 2015-09-01.
I tried using filter but unsuccessfully. Give me some knowledge on this, please.
If your object is fetching data from db and timestamp is returned properly, and your date is formatted as 'yyyy-MM-dd', this should work.
{{item.createdOn| date:'yyyy-MM-dd'}}
Otherwise, format your string as a Date. (This is detailed in other answers.)
$scope.dateOnly= function(timestamp) {
return new Date(timestamp);
}
will help
You need to use Angular filter But Date filters only work with Date objects so first thing you need to convert your strings into Date object.
<div ng-repeat="item in array">
{{getDateFormat(item.createdOn)|date:'yyyy-MM-dd'}}
</div>
Controller:
$scope.array = [{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
}, {
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}];
$scope.getDateFormat = function(timestamp) {
return new Date(timestamp);
}
Plunker
The short answer:
Date filter in Angular works better with Date objects.
Please run this code snippet:
angular.module('app',[]).controller('a',function($scope){
$scope.a='2012-08-30 13:30:00'
$scope.b=new Date('2012-08-30 13:30:00')
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app=app ng-controller=a>
{{a|date:'mm-dd-yy'}}
<hr>
{{b|date:'mm-dd-yy'}}
</div>
This is the fix for you code:
var obj= [{
"user": "345",
"createdOn": new Date("2015-09-01 13:17:22")
},
{
"user": "432",
"createdOn": new Date("2015-09-01 13:27:56")
}
]
You can see the example that when I use date object it works.
If you got the object from external sources you can convert it to Date objects. using this code:
for(var i=0;i<obj.length;i++) obj[i].createdOn=new Date(obj[i].createdOn)
You can create your own custom filter in this case,
Try this,
HTML :
<div ng-controller="MainCtrl">
<div ng-repeat="data in datas">
{{data.createdOn | dateOnly}}
</div>
</div>
angularjs :
angular.module("myapp", []).controller('MainCtrl', ["$scope", function($scope){
var data = [
{
"user": "345",
"createdOn": "2015-09-01 13:17:22"
},
{
"user": "432",
"createdOn": "2015-09-01 13:27:56"
}];
$scope.datas = data;
}])
.filter("dateOnly", function(){
return function(input){
return input.split(' ')[0]; // you can filter your datetime object here as required.
};
});
jsFiddle

Categories

Resources