Loading data from JSON file in to Javascript object - javascript

I am trying to access the data from my JSON file to be used within my controller for further manipulation using Angular. To start, here are the first couple entries of the file 'cards.json'
{ "TheGrandTournament": [
{
"name": "Buccaneer",
"cardSet": "The Grand Tournament",
"type": "Minion",
"rarity": "Common",
"cost": 1,
"attack": 2,
"health": 1,
"text": "Whenever you equip a weapon, give it +1 Attack.",
"collectible": true,
"playerClass": "Rogue",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
"name": "Competitive Spirit",
"cardSet": "The Grand Tournament",
"type": "Spell",
"rarity": "Rare",
"cost": 1,
"text": "<b>Secret:</b> When your turn starts, give your minions +
"collectible": true,
"playerClass": "Paladin",
"img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
"mechanics": [{"name": "Secret"}]
}, ...
]}
I have had success with accessing the information from my view using this code
<div ng-controller="CardCtrl">
<button id="loadbtn" ng-click="load()">Load</button><br>
<div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
<pre>{{ cards.name }}</pre>
</div>
</div
My controller looks like this:
angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.method = 'GET';
$scope.url = 'cards.json';
$scope.load = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.data = response.data;
console.log("Read file", $scope.url, "successfully.");
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
};
$scope.cardData = angular.fromJson($scope.data[0]);
console.log($scope.cardData);
}]);
The error returned when trying to output $scope.cardData to a console log is
"TypeError: Cannot read property '0' of undefined".
I tried then parsing the data from the json object using angular.fromJson() but it is not working as I am intending.

You should move $scope.data into the success callback of the promise:
$http({method: $scope.method, url: $scope.url}).
then(function(response) {
$scope.cardData = response.data.TheGrandTournament;
console.log("Read file", $scope.url, "successfully.");
console.log($scope.cardData);
}, function(response) {
$scope.data = response.data || "Request failed";
console.log("Error reading", $scope.url, ".");
});
// scope parameter data is not accessible here, as it's not yet added
//$scope.cardData = angular.fromJson($scope.data[0]);
//console.log($scope.cardData);
}]);

Replace:
$scope.data = response.data;
with:
$scope.data = response.data.TheGrandTournament;

Try to replace:
$scope.cardData = angular.fromJson($scope.data[0]);
with:
$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);

Related

div in ng-repeat is not getting updated?

I am getting a response from http get request and Iam using the response to iterate in the data
<div id="container" ng-app="myApp" ng-controller="myctrl">
<div ng-repeat="profile in profiles">
<p>{{profile.username}}</p>
</div>
</div>
This is for adding one profile on click
<input ng-click="addProfile()" type="button" value="add Profile" />
Here is my get request in the controller
var app = angular.module('myApp', []);
app.controller('myctrl', function($scope, $http) {
$scope.profiles = [];
$http.get("test1.json")
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
alert("af");
$scope.items = response.data.profiles; //Response is provided below
$scope.profiles.push($scope.items);
console.log($scope.profiles); //gives the update Array
});
});
});
response of my get request of test1.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 1",
},
{
"type": "Student ",
"username": "Username 2",
}
]
}
response of my get request of test2.json
{
"Id": "44442232",
"profiles": [
{
"type": "Friend",
"username": "Username 4",
},
{
"type": "Student ",
"username": "Username 5"
}
]
}
I have tried console.log after updating in the array.The array is updated but the div in ng-repeat is not getting updated?
Please close your JSON calling request by putting ')' at the end. There is no error apart from this and the same code works for me fine.
// Code goes here
var myApp = angular.module("myApp", []);
myApp.controller("myctrl", function($scope, $http) {
$http.get('test1.json')
.then(function(response) {
$scope.profiles = response.data.profiles; //Response is provided below
});
$scope.addProfile = function(){
$http.get('test2.json')
.then(function(response) {
$scope.items = response.data.profiles; //Response is provided below
angular.forEach($scope.items, function(value) {
$scope.profiles.push(value);
});
console.log($scope.profiles);
});
};
});
Please find this updated js code and check. Once it is fixed let me know. happy coding :)
First of all I don't think you need $scope.$apply() to trigger the digest cycle. You are in angular context.
Second, you are missing a ')' when you are calling .then(). You currently have '.then(function(){};'
Third, your response object should not have a comma after the username property if that property is the last one in the object.
Also do you have a silent fail, or it is an error in the console, and the processed html for the ng-repeat is blank or you get the angular interpolation syntax {{profile.username}}?

Advice on how to access child objects from JSON in Angular JS

I have created the following controller in Angular, and I'm trying to access some child objects in the returned JSON.
Controller:
var app = angular.module("MyApp", []);
app.controller("FAQCtrl", function($scope, $http) {
$scope.dataLoaded = false;
$http.get('config/data.json', {
})
.success(function(data, status, headers, config) {
$scope.config = data;
$scope.dataLoaded = true;
}).
error(function(data, status, headers, config) {
window.alert("Sorry! There has been a problem!\n\nPANIC!")
});
});
The JSON that's returned is in this format :
{
"entryList":
{
"totalEntries": 237,
"incEntries": 10,
"offset": 0,
"loggingURL": "/action/logStatistics?action1=%27client%d%27",
"entry":
[
{
"catID": "delivery",
"entryID": "delivery-charges",
"subcatID": "delivery-options",
"question": "What are your delivery charges?"
},
{
"catID": "returns-and-refunds",
"entryID": "online-returns-policy",
"subcatID": "returns-policy",
"question": "What is your online returns policy?"
},
{
"catID": "delivery",
"entryID": "track-delivery",
"subcatID": "order-status",
"question": "How can I track my delivery/order?"
},
{
"catID": "delivery",
"entryID": "click-and-collect",
"subcatID": "delivery-options",
"question": "Do you offer Click and Collect or Collect +?"
},
{
"catID": "products-and-services",
"entryID": "makeover",
"subcatID": "services",
"question": "Can I come in for a free makeover and skin consultation?"
},
{
"catID": "delivery",
"entryID": "how-long-for-delivery",
"subcatID": "delivery-queries",
"question": "How long will it take for my products to be delivered?"
}
]
}
}
I'd like to be able to return the details of each of the "entry" sections of the feed, but I'm struggling to make the following work:
<div ng-repeat="item in entryList">
{{item.entryID}}
<br />
</div>
Could any one give me an idea on how I can easliy access the child sections?
Thanks
There seem to be several problems here.
You are referring to entryList in ng-repeat but you don't have a variable called entryList in your scope. Once your data is returned you will need to assign $scope.entryList = data.entryList.entry;in the success portion.
If this is data that is required by the directive on your page on load then you should pass it into your controller rather than populating it after the controller is loaded. This can be done by using resolve. Here's more info on that
https://thinkster.io/egghead/resolve
On your ajax call you're storing all data at $scope.config so either store them elsewhere or use config on ng-repeat
<div ng-repeat="item in config.entryList.entry">
{{item.entryID}}
<br />
</div>
Otherwise if you want to store it on another variable than :
var app = angular.module("MyApp", []);
app.controller("FAQCtrl", function($scope, $http) {
$scope.dataLoaded = false;
$http.get('config/data.json', {
})
.success(function(data, status, headers, config) {
$scope.config = data;
$scope.entrylist = data.entryList.entry;
$scope.dataLoaded = true;
}).
error(function(data, status, headers, config) {
window.alert("Sorry! There has been a problem!\n\nPANIC!")
});
});

Retrieving posts by id

I am receiving a JSON object from WordPress which looks like this
{
"ID": 4164,
"title": "24 Horas Non-Stop con Marco Carola",
"status": "publish",
"type": "post",
"author": {
"ID": 11,
"username": "VIlma Quiros",
"registered": "2015-04-16T07:04:04+00:00",
"meta": {
"links": {
"self": "http://urbanetradio.com/wp-json/users/11",
"archives": "http://urbanetradio.com/wp-json/users/11/posts"
}
}
},
"content": "<p class=\"p2\"><a href=
here is my service
.service('FreshlyPressed', function($http, $q) {
return {
getBlogs: function($scope) {
var posts = [];
$http.get('http://urbanetradio.com/wp-json/posts')
.success(function(result) {
$scope.posts = result;
})
},
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/postId';
return $http.get(url);
}
});
and here the controller
.controller('NewsCtrl', function($scope, FreshlyPressed) {
$scope.posts = [];
$scope.doRefresh = function() {
$scope.posts = FreshlyPressed.getBlogs($scope);
$scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh();
});
and here is what I want:
in this view I display only the title and the date of the posts, this is the main view
<a ng-href="#/tabs/news/{{post.ID}}">
<h2 ng-bind-html="post.title"></h2>
<p>{{:: post.date | date}}</p>
</a>
when you click in that title you should be redirected to the entired post which is here, in the secondary view
<div class="item item-text-wrap item-image padding">
<div class="special-font" ng-bind-html="post.content"></div>
</div>
the routes
//the route for the main view
.state('tabs.news', {
url: '/news',
views: {
'tab-news': {
templateUrl: 'templates/tab-news.html',
controller: 'NewsCtrl'
}
}
})
//the route for the second view where you will see the entire post
.state('tabs.post-detail', {
url: '/news/:postId',
views: {
'tab-news': {
templateUrl: 'templates/tab-post-detail.html',
controller: 'PostDetailCtrl'
}
}
})
I get this error
GET http://urbanetradio.com/wp-json/posts/postId 404 (Not Found)
I guess you need to change this function like this
getPostById: function(postId) {
var url ='http://urbanetradio.com/wp-json/posts/'+ postId;
return $http.get(url);
as per you code postId is parameter that you want to replace in string than you should append value in string as in code
you need to call method like
FreshlyPressed.getPostById(1);//1 is postid value

angularjs $resource result jsonp

I want to send a request my server via JSONP and get results but I could not do it.
My server link that returns json result.
$scope.data= [
{ id: 1, name:"D1" },
{ id: 2, name:"D2" },
{ id: 3, name:"D3" },
{ id: 4, name:"D4" }
];
I am using $resource in angularjs controller like this:
app.controller("MydataListController", function($scope, $resource, $http){
var dataquery = $resource("http://192.6.4.44/DataProvider/Search/",
{ },
{ get: {method: "JSONP"} , params:{ term: "port" } });
$scope.result = dataquery.get();
console.log($scope.result);
});
But my $scope.result retuns like this:
Resource {$promise: Object, $resolved: false, $get: function, $save:
Since $resource makes an asynchronous call, you need to pass a handler function to the get method, like so:
app.controller("MydataListController", function($scope, $resource, $http){
var dataquery = $resource("http://192.6.4.44/DataProvider/Search/",
{ },
{ get: {method: "JSONP"} , params:{ term: "port" } });
dataquery.get({}, function(data) {
$scope.result = data;
console.log($scope.result);
});
});
FYI: I haven't tested this code!

Angular JS TypeError: Cannot read property 'id' of undefined on Route

I'm in the process of learning a bit of AngularJS and I've hit a stumbling block. I can retrieve my jSON and feed it into the frontend, but my problem is coming when I'm going to a new view. My ID is not coming in correctly. Basically if click on my item that has a id 1 its displaying id 14. Or I get TypeError: Cannot read property '14' of undefined
Any ideas would be really helpful.
jSON
[
{
"id": 14,
"title": "new post",
"excerpt": "EXCERPT",
"content": "ushajsd"
},
{
"id": 10,
"title": "last post",
"excerpt": "test",
"content": "test"
},
{
"id": 4,
"title": "middle post",
"excerpt": "contents to post",
"content": "contents to post"
},
{
"id": 1,
"title": "Hello world!",
"excerpt": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
"content": "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!"
}
]
AngularJS
//Create main module
var module = angular.module('module', [''])
//Services
module.factory('posts', function($http) {
return {
getAsync: function(callback) {
$http.get('/wp-content/themes/ajax/ajax.php').success(callback);
}
};
});
// Set up our mappings between URLs, templates, and controllers
function caseStudyConfig($routeProvider) {
$routeProvider.
when('/casestudy/:id', {
controller: caseCtrl,
templateUrl: '/wp-content/themes/templates/casestudy.php'
}).
otherwise({
redirectTo: '/'
});
}
// Set up our route so the service can find it
module.config(caseStudyConfig);
//Controllers
function homeCtrl (posts, $scope) {
posts.getAsync(function(data) {
$scope.content = data;
});
}
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = data[$routeParams.id];
});
}
Assuming the data property in your getAsync callback is a representation of the JSON you've posted, I think it's because you're attempting to access the object by it's position in the array and not by its id property. If you're using underscore / lodash, you could fix this easily like so:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
// Find the object with id which matches id in route params
$scope.content = _.findWhere(data, { id: $routeParams.id });
});
}
Or you could write your own loop to retrieve the correct object from the collection:
function caseCtrl (posts, $scope, $routeParams) {
posts.getAsync(function(data) {
$scope.content = getObjectById(data, $routeParams.id);
});
function getObjectById(collection, id) {
for (var i = 0, obj; i < collection.length; i ++) {
obj = collection[i];
if (obj.id === id) {
return obj;
}
}
return null;
}
}

Categories

Resources