AngularJS display JSON data in table - json

I am using AngularJS with RESTAPI, I am able to get the customers data sent from server in a JSON format. My Angular code snippet as below:
app.factory("services", ['$http', function($http) {
var serviceBase = '/api/album';
var obj = {};
obj.getCustomers = function(){
return $http.get(serviceBase);
};
return obj;
}]);
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
});
Here is my JSON data:
{
"data": [
{
"id": "1",
"artist": "Gotye75",
"title": "Making Mirrors7"
},
{
"id": "100",
"artist": "ytttt5",
"title": "1231"
},
{
"id": "101",
"artist": "65",
"title": "565444555"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
},
{
"id": "109",
"artist": "ytrer",
"title": "yt"
}
]
}
I am able to display the JSON data in table if my JSON does not contain the "data" hear. However if my jSON data comes with "data" header, it is unable to display. I am asking, what are the solution in Angular to parse the JSON object.
For example if it is in BackboneJS, i can simply do
parse: function (response) {
//alert(JSON.stringify(response.data));
return response.data;
}
How can i do it in Angular?

$http resolves its promises with a response object. The data is accessed via the response object's data property. So to get to the array, you'd have to use
$scope.customers = data.data.data;
$http's promise is enhanced with a .success() convenience method which unwraps the response object...
services.getCustomers().success(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});

I solved it by
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
//notice that i added the third data
$scope.customers = data.data.data;
});
});

Related

Im trying to get values of the following JSON object and display them in html using angularness

In the following JSON object, I'm trying to get the value of the streets
Get business profile data :
{
"_id": "56dd1bd4d0561b403f683bfd",
"UserId": "56b301516b9064189049acb5",
"WebURL": "2",
"PhoneNumber": "3",
"ContactEmail": "1#gmail.com",
"AdditionalInfo": "",
"__v": 0,
"DateCreated": "2016-03-07T06:12:36.957Z",
"Categories": [],
"Addresses": [{
"Street": "1",
"City": "1",
"State": "1",
"Country": "1",
"SuiteNumber": "1",
"_id": "56dd1bd4d0561b403f683bfe"
}]
}
So far this is what I have:
Info.GetData()
.success(function (response){
$scope.Data = response;
})
.error(function (response, status) {
alert("Can Not Retrieve Company Info, Please Contact Admin")
})
<div ng-repeat="x in Data.Addresses">
{{x.Street}}
</div>
I still can't get it working.
Assuming your Info.GetData() is making a $http call and you are using success instead of then, you will still have to use then wherever there is a promise. If you are doing this
return
angular.module('app').factory('Info', function($http) {
return {
getData: function() {
return $http.get('url');
};
};
});
in your Info.getData(). You could instead do
return
angular.module('app').factory('Info', function($http) {
return {
getData: function() {
return $http.get('url').then(function(response)
{
return response.data;
}
};
};
});`
Also, you need to check if your service is returning a promise. If its a promise you should resolve it. You can't assume that your promise has a .success().

Meteor JSON Method and Call in template

I am trying to call a Meteor method with a parsed json doc to use in my template. None of my calls work and I then need advise on how to display (maybe I should save this part for another post - but any suggestions would be helpful) in template with helpers. I am new to meteor and javascript.
Json doc
{
"sports-content": {
"sport-event": [{
"event-metadata": {
"league": "NCAA Basketball",
"event-type": "0",
"league-details": "NCAAB",
"event-date-time": "12/18/2015 07:00 PM",
"eventNum": "3000460",
"status": "",
"off-the-board": "False"
},
"team": [{
"team-metadata": {
"alignment": "Home",
"nss": "526",
"openNum": "526",
"name": {
"full": "Clemson"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}, {
"team-metadata": {
"alignment": "Away",
"openNum": "525",
"nss": "525",
"name": {
"full": "South Carolina"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "-1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}]
}],
"sports-meta-data": {
"doc-time": "42353.5979256944"
}
}
}
server.js
Meteor.startup(function () {
Meteor.methods({
sportsFeed:function(){
//console.log(JSON.parse(Assets.getText('ncaab.json')));
var feed = {};
var feed = JSON.parse(Assets.getText("ncaab.json"));
return feed;
}
});
});
Template.html
<template name="tabsOne">
<p>{{display}}</p>
</template>
Template.js
Template.tabsOne.helpers({
display: function(){
Meteor.call('sportsFeed', function(error, result){
if(error){
console.log("error", error);
}
if(result){
console.log('success');
}
});
}
});
If the json file is from your local, thinking about save it into Mongo and then publish it to the client
First, you need to create a collection called SportContent and on the server side, just make
SportContent.insert(JSON.parse(Assets.getText("ncaab.json")));
and then, do the normal publication to the client
If the json file is not on your local side (as in, you get it from rest call service), use wrapAsync to wrap the Http.call, then trigger the rest call and return the result. On your client side, you will get the response
Example on the server side to connect to the rest api
Meteor.methods({
'updateFeed': function () {
var httpCall = Meteor.wrapAsync(HTTP.call);
var result = httpCall('GET', url, {headers: headers});
....
}
});

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

How to display data from a json file in angularjs?

I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}

evaluating json object returned from controller and attaching it to prepopulate attribute of tokeninput

I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}