How to fetch data from json in angularjs Form - angularjs

How to call the data from json in angularjs form without using backend. i have written this code and here m unable to find a way in last to get data from the json file. someone please help me to move forward from here.
code
$scope.count = $scope.newPreAuth.length;
};
//Delete newPreAuth - Using AngularJS splice to remove the preAuth row from the newPreAuth list
//All the Update newPreAuth to update the locally stored newPreAuth List
//Update the Count
$scope.deletenewPreAuth = function (preAuth) {
$scope.newPreAuth.splice($scope.newPreAuth.indexOf(preAuth), 1);
getLocalStorage.updatenewPreAuth($scope.newPreAuth);
$scope.count = $scope.newPreAuth.length;
};
}]);
//Create the Storage Service Module
//Create getLocalStorage service to access UpdateEmployees and getEmployees method
var storageService = angular.module('storageService', []);
storageService.factory('getLocalStorage', function () {
var newPreAuthList = {};
return {
list: newPreAuthList,
updatenewPreAuth: function (newPreAuthArr) {
if (window.localStorage && newPreAuthArr) {
//Local Storage to add Data
localStorage.setItem("newPreAuth", angular.toJson(newPreAuthArr));
}
newPreAuthList = newPreAuthArr;
},
getnewPreAuth: function () {
//Get data from Local Storage
newPreAuthList = angular.fromJson(localStorage.getItem("newPreAuth"));
return newPreAuthList ? newPreAuthList : [];
}
};
});
Json Code
PreAuth:
======================
URL:http://dev.xxx.com:8080/xxx/preAuth
TYPE:POST
X-Auth-Token t3Z10HGEiYFdzq9lGtr18ycdeAAXmWBEI64rQAJcAte6Ka8Tz96IAhuXHSgpiKufsd
{
"preAuth": {
"claimbId": "newPreAuth",
"claimbStatus": "new",
"patientInfo": {
"patientName": "name",
"gender": "Male",
"dob": 950639400000,
"age": 21,
"contactNumber": 9987654356,
"tpaMemberId": 950639400121,
"policyNumber": "ABC12615627",
"corporateName": "ABC",
"EmployeeId": "XYZ10232",
"otherInsurance": {
"isOtherInsurance": true,
"playerName": "xyx",
"details": "sdfdsafdsfdsf"
},
"familyPhysician": {
"isFamilyPhysician": true,
"physicianName": "fsdf"'c
"physicianContactNumber": 7878748728,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"isFamilyPhysician": false,
"address": {
"address1": "Hosa road",
"address2": "Basapura",
"city": "Bangalore",
"state": "Karnataka",
"country": "India",
"pincode": "560100"
}
},
"medicalInfo": {
"illnessType": "cancer",
"clinicalFinding": "description",
"ailmentDuration": "2 months",
"ailmentHistory": "description",
"illnessCause": "alcohol",
"provisionalDiagnosis": [
{
"diagnosisName": "abc",
"diagnosisICDCode": "121423"
},
{
"diagnosisName": "xyz",
"diagnosisICDCode": "434543"
}
],
"differentialDiagnosis": [
{
"diagnosisName": "afasdbc",
"diagnosisICDCode": "12431423"
},
{
"diagnosisName": "fdxyz",
"diagnosisICDCode": "434sdf543"
}
],
"clinicalObservations": {
"BP": "120/80",
"CVS": "126",
"P.A.": "abc",
"R.S.": "aa",
"CNS": "dd",
"others": "others"
},
"maternityDetails": {
"maternityType": "G",
"L.M.P.": 950639400000,
"E.D.D.": 950639400000
},
"accidentDetails": {
"accidentCause": "xyz",
"accidentDate": 950639400000,
"isPoliceComplaint": true,
"firNumber": "asfsafds"
},
"pastIllness": [
{
"pastIllnessType": "Diabetes",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Hypertension",
"isPresent": true,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
},
{
"pastIllnessType": "Other",
"isPresent": false,
"NoOfMonth": 2,
"NoOfYear": 5,
"illnessSince": 950639400000
}
]
},
"treatmentInfo": {},
"billingInfo": {},
"documents": [
{
"documentId": 12345,
"documentMetadata": {
"documentName": "discharge summary",
"date": 950639400000,
"version": "1.1",
"viewedStatus": false,
"link": "link to view/download document"
}
},
{
"documentId": 12346,
"documentMetadata": {
"documentName": "medical summary",
"date": 950639400000,
"version": "1.0",
"viewedStatus": true,
"link": "link to view/download document"
}
}
]
}
}

I created sample ,it worked this way
// Code goes here
var app = angular.module('app',[]);
app.controller('sample', function($scope,$http){
$scope.name = "advaitha";
$http.get('test.json').then(function(data){
console.log(data.data);
});
})
here is the plunker example
using HTML5 localStorage would require you to serialize and deserialize your objects before using or saving them.
For example:
var myObj = {
firstname: "kisun",
lastname: "rajot",
website: "https://www.kisun.com"
}
//if you wanted to save into localStorage, serialize it
window.localStorage.set("empData", JSON.stringify(myObj));
//unserialize to get object
var myObj = JSON.parse(window.localStorage.get("empData"));
Created a plunker based on your code am able save and retrieve the json data with your code. Please check here

Related

How do I sort this array by date?

I'm trying to sort the dates from this external API in my latestResults array by latest on top to oldest on bottom but can't seem to figure out how.
Right now they're displayed with the oldest date first and it's working fine, but it's in the wrong order for me.
I tried using result in latestResults.reverse() but that just reverses the 7 items currently in the array.
HTML:
<div v-for="result in latestResults" v-bind:key="result.latestResults">
<small">{{ result.utcDate }}</small>
</div>
Script:
<script>
import api from '../api'
export default {
data () {
return {
latestResults: [],
limit: 7,
busy: false,
loader: false,
}
},
methods: {
loadMore() {
this.loader = true;
this.busy = true;
api.get('competitions/PL/matches?status=FINISHED')
.then(response => { const append = response.data.matches.slice(
this.latestResults.length,
this.latestResults.length + this.limit,
this.latestResults.sort((b, a) => {
return new Date(b.utcDate) - new Date(a.utcDate);
})
);
setTimeout(() => {
this.latestResults = this.latestResults.concat(append);
this.busy = false;
this.loader = false;
}, 500);
});
}
},
created() {
this.loadMore();
}
}
</script>
The JSON where I'm getting matches like this that has utcDate:
{
"count": 205,
"filters": {
"status": [
"FINISHED"
]
},
"competition": {
"id": 2021,
"area": {
"id": 2072,
"name": "England"
},
"name": "Premier League",
"code": "PL",
"plan": "TIER_ONE",
"lastUpdated": "2021-02-01T16:20:10Z"
},
"matches": [
{
"id": 303759,
"season": {
"id": 619,
"startDate": "2020-09-12",
"endDate": "2021-05-23",
"currentMatchday": 22
},
"utcDate": "2020-09-12T11:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": "Regular Season",
"lastUpdated": "2020-09-13T00:08:13Z",
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
},

How can I change the attribute in dataset of Fusionchart?

Hi I am implementing a chart in my Angularjs Application, You can see this plunker http://jsfiddle.net/fusioncharts/73xgmacm/ The thing which I want to achieve is to change the value attribute to profit. How can I do this ? I want to display profit not values.
Regards
After 2 days I finally find out the answer. The thing is You cannot change the Fusionchart attribute value but you can change the attribute of your API once you fetched. I used a loop after I fetched the API and replace the 'profit' attribute with value in this way I made the chart. Yes The thing which i had been ignoring was the use of 'variable' instead of scope. If you see this example you would understand Example Here. I am sharing my code May be it helps someone else too.
Give below is my json array which i called tps.json
[
{
"index": "1",
"variantoption": "fan-green",
"company": "sk fans",
"quantity": "650",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "2",
"variantoption": "fan-white",
"company": "al ahmed fans",
"quantity": "450",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "3",
"variantoption": "fan-purple",
"company": "asia fans",
"quantity": "350",
"profit": "78296",
"loss": "8457",
"year": "2016"
},
{
"index": "4",
"variantoption": "fan-yellow",
"company": "falcon fans",
"quantity": "250",
"profit": "78296",
"loss": "8457",
"year": "2016"
}
]
and here is my controller
$http.get('js/tps.json').success(function (data) {
var chartdata = data;
var arrLength = chartdata.length;
console.log(arrLength);
for (var i = 0; i < arrLength; i++) {
if (chartdata[i]['profit'] && chartdata[i]['index']) {
chartdata[i].value = chartdata[i].profit;
delete chartdata[i].profit;
chartdata[i].label = chartdata[i].index;
delete chartdata[i].index;
console.log(chartdata);
}
}
console.log(chartdata);
FusionCharts.ready(function () {
var tps = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly",
"xaxisname": "Month",
"yaxisname": "Revenue",
"numberprefix": "$",
"showvalues": "1",
"animation": "1"
},
"data" : chartdata
}
});
tps.render();
});
}
);
}
-Stay foolish stay hungry

Error in routing with id parameter, link works but displays no data

I am having an issue with retrieving the stored data (within MongoDB) by way of an :id parameter. The link works and takes me to the specified url (./contests/1), but the data doesn't show up. When querying within the mongo CMD with (db.contests.find( {id:1} )) the correct object's data is displayed correctly.
route/contest.js
router.route("/contests/:id")
.get(function(req, res, next) {
Contest.findOne({id: req.params.id}, function(err, contest) {
if(err) {
res.send(err);
}
res.json(contest);
});
service/contestService.js
app.factory("contestService", ["$http", "$resource",
function($http, $resource)
{
var o = {
contests: []
};
function getAll() {
return $http.get("/contests").then(function(res) {
angular.copy(res.data, o.contests);
});
}
function get(id) {
return $resource('/contests/:id');
}
o.getAll = getAll;
o.get = get;
return o;
}]);
})();
controller/contestController.js
var app = angular.module("sportsApp.controllers.contest,["ui.router"]);
app.config(["$stateProvider", function($stateProvider) {
$stateProvider.state("contest", {
parent: "root",
url: "/contests/:id",
views: {
"container#": {
templateUrl: "partials/contests",
controller: "ContestController"
}
}
});
}
]);
app.controller("ContestController", ["$scope","contestService", "$stateParams", function($scope, contestService, $stateParams) {
var contest_id = $stateParams.id;
$scope.contest = contestService.get({id: contest_id});
}]);
})();
Contest Schema
var mongoose = require("mongoose");
var ContestSchema = new mongoose.Schema(
{
id: Number,
tags: String,
matchups: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Matchup"
}],
usersWhoJoined: [{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}]
});
mongoose.model("Contest", ContestSchema);
Any assistance or advice would be much appreciated due to the fact that I am learning as I go with the MEAN stack and have little to no experience with it.
I am looking to display the specific contest's matchups in which displays two teams and other variables. This is my json file that I mongoimported in order to create the object of the contests collection within MongoDB:
{
"id": 1,
"tags": "NBA",
"matchups": [{
"matchupId": 1,
"selectedTeam": "",
"matchupWinner": "Atlanta",
"nbaTeams": [{
"team": "Portland",
"logo": "stylesheets/nbalogos/Portland-Trail-Blazers-Logo.png"
}, {
"team": "Atlanta",
"logo": "stylesheets/nbalogos/atl-hawks.png"
}]
}, {
"matchupId": 2,
"selectedTeam": "",
"matchupWinner": "Dallas",
"nbaTeams": [{
"team": "Dallas",
"logo": "stylesheets/nbalogos/Dallas-Mavericks.png"
}, {
"team": "Detroit",
"logo": "stylesheets/nbalogos/DET.png"
}]
}, {
"matchupId": 3,
"selectedTeam": "",
"matchupWinner": "Golden State",
"nbaTeams": [{
"team": "Golden State",
"logo": "stylesheets/nbalogos/GSW.png"
}, {
"team": "Memphis",
"logo": "stylesheets/nbalogos/Memphis-Grizzlies.png"
}]
}, {
"matchupId": 4,
"selectedTeam": "",
"matchupWinner": "Oklahoma City",
"nbaTeams": [{
"team": "Oklahoma City",
"logo": "stylesheets/nbalogos/OKC-Thunder.png"
}, {
"team": "Pheonix",
"logo": "stylesheets/nbalogos/Pheonix-Suns.jpg"
}]
}, {
"matchupId": 5,
"selectedTeam": "",
"matchupWinner": "Utah",
"nbaTeams": [{
"team": "Sacremento",
"logo": "stylesheets/nbalogos/Sacremento-Kings.jpg"
}, {
"team": "Utah",
"logo": "stylesheets/nbalogos/Utah-Jazz.jpg"
}]
}]
}
I want to create each contest in this format.
I have no idea what relevance the actual data has to this issue, so let's start with $scope.contest, since there seems to be a problem with the way you're accessing data.
// ContestController
$scope.contest = contestService.get({id: contest_id});
OK, so you're calling the contestService.get method with an object, let's say it's {id: 2}. Let's look at that method and call it with that object.
// contestService
function get(id) {
return $resource('/contests/' + id);
}
If using our dummy data, if you call get({id: 2}), you now have an Angular resource at the URL /contests/[object Object] because your object gets converted into a string. Your method would work if called using the value at the id property of that object, like:
// ContestController
$scope.contest = contestService.get(contest_id);

JSON string array is always null

I have some JSON data rendered server-side to be available in the client page. In the HTTP response it looks correct:
digitalData = {
"page": {
"pageInfo": {
"geoRegion": "US",
"onsiteSearchResults": 38,
"onsiteSearchTerm": "leather",
"sysEnv": "HAMP"
},
"category": {
"dirID": 2,
"pageTemplate": "/store/search.aspx",
"pageType": "Search"
},
"attributes": {
"searchType": "standard",
"refinementCategory": "10001",
"searchFilters": ["50859"]
}
},
"user": {
"profile": {
"profileInfo": {
"profileID": "{C0A253A9-AD6E-4B6B-A313-3D215704D0FB}",
"returningStatus": "new"
}
},
"segment": {
"persona": ["EXPERT"]
}
},
"cart": {
"cartID": "2508d65f-6495-4256-8125-75767b847e45",
"numItems": 0
},
"version": "1.0"
};
But when I examine the DOM through Dev Tools Elements or Console, the searchFilters string array in the above JSON is always null. I have no client side code that refers to that object at all. How/why is it going from correct in the HTTP Response to null in the DOM? I've validated the JSON in JSONLint and it is valid.
The JSON is valid. Append square brackets and try again.
var objArray= [{
"page": [{
"pageInfo": [{
"geoRegion": "US",
"onsiteSearchResults": 38,
"onsiteSearchTerm": "leather",
"sysEnv": "HAMP"
}],
"category": [{
"dirID": 2,
"pageTemplate": "/store/search.aspx",
"pageType": "Search"
}],
"attributes": [{
"searchType": "standard",
"refinementCategory": "10001",
"searchFilters": ["50859"]
}]
}],
"user": [{
"profile": {
"profileInfo": {
"profileID": "{C0A253A9-AD6E-4B6B-A313-3D215704D0FB}",
"returningStatus": "new"
}
},
"segment": {
"persona": ["EXPERT"]
}
}],
"cart": [{
"cartID": "2508d65f-6495-4256-8125-75767b847e45",
"numItems": 0
}],
"version": "1.0"
}];
function getDetails(){
document.getElementById("demo").innerHTML = "Length of Array = " + objArray.length;
document.getElementById("element").innerHTML = "0th Element of Array = " + objArray[0];
document.getElementById("elementInfo").innerHTML = "Element at 0th position Array = " + objArray[0].page[0].pageInfo;
document.getElementById("elementInfo2").innerHTML = "Element at 00th position Array = " + objArray[0].page[0].pageInfo[0].geoRegion;
}
<button onclick=getDetails()> Check </button>
<p id="demo"></p>
<p id="element"></p>
<p id="elementInfo"></p>
<p id="elementInfo2"></p>

Angular-Leaflet-Directive + JSON markers

Try create Leaflet Map with clustering markers in my app. Using for this Angular Leaflet Directive plugin.
It's work with example controller and JSON data, but I have other JSON with other data format and have problem with get lattitude and longitude parameters for creating markers array on my map.
My Controller
app.controller("BasicFirstController", [ "$scope", "$http", function($scope, $http) {
var addressPointsToMarkers = function(points) {
return points.map(function(ap) {
return {
layer: 'realworld',
lat: ap[0],
lng: ap[1],
message: ap[2]
};
});
};
angular.extend($scope, {
center: {
lat: 53.13207624721133,
lng: 26.01689853383789,
zoom: 15
},
events: {
map: {
enable: ['moveend', 'popupopen'],
logic: 'emit'
},
marker: {
enable: [],
logic: 'emit'
}
},
layers: {
baselayers: {
osm: {
name: 'OSM',
url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
type: 'xyz'
},
overlays: {
realworld: {
name: "Real world data",
type: "markercluster",
visible: true
}
}
}
});
$http.get("sample.json").success(function(data) {
$scope.markers = addressPointsToMarkers(data);
});
}]);
Work with this JSON format
[
[-37.8839, 175.3745188667, "571"],
[-37.8869090667, 175.3657417333, "486"],
[-37.8894207167, 175.4015351167, "807"],
[-37.8927369333, 175.4087452333, "899"],
[-37.90585105, 175.4453463833, "1273"]
]
Need work with this JSON format
{
"posts": [
{
"ID": "1",
"title": "Title",
"tag": "tag1",
"lat": "53.11691211703813",
"lng": "26.03631556034088",
"thumb": "getImage-24-100x100.jpg",
"fullimg": "getImage-24.jpg",
"imgs": [
{
"imgurl": "getImage-24-300x200.jpg"
}
],
"place": "Place",
"type": "Photo",
"period": "War",
"year": "1985",
"url": "site.com",
"author": "author"
},
{
"ID": "2",
"title": "Title2",
"tag": "tag2",
"lat": "53.11691211703813",
"lng": "26.03631556034088",
"thumb": "getImage-24-100x100.jpg",
"fullimg": "getImage-24.jpg",
"imgs": [
{
"imgurl": "getImage-24-300x200.jpg"
}
],
"place": "Place",
"type": "Photo",
"period": "War",
"year": "1935",
"url": "site.com",
"author": "author"
}
]
}
How get data with lat and lng from JSON for markers array?
Here is what worked for me with a JSON file sent from server, to publish ALL markers at once:
Then with $HTTP I can "get" the data, but you will have to loop through it and push details to a new $scope array:
$scope.markers = []
$http.get('JSONfilePath').then(function (responseData) {
for (var i = 0; i < responseData.data.length; i++){
$scope.markers.push({
lat: responseData.data[i].latitude,
lng: responseData.data[i].longitude
})
}
})
In the HTML file, it's pretty straight forward:
<leaflet lf-center="center" defaults="defaults" markers="markers" width="90%" height="800px"></leaflet>

Resources