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!")
});
});
Related
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}}?
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]);
I have a Json that contains this:
[
{
"_id": "00000",
"title": "",
"genre": "fantasy",
"year": "1999",
"image": "photo.jpg"
}
]
I use AngularJs and I want show image in my page html. This is the code:
<div>
<h2>Films</h2>
<div>
<div ng-repeat="book in lista">
<div>
<img ng-src="{{book.cover}}" style="width: 256px; height: 128px;">
</div>
</div>
</div>
</div>
and this is my controller:
var modulo = angular.module('progetto', ['ngRoute']);
modulo.config(function ($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'list.html',
controller: 'listController'
})
});
modulo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
}).
error(function (data, status) {
$scope.lista = "Request failed";
});
});
how do I show the photo? Because the photo is a jpg. Thanks!
You might want to call $scope.$apply() after every http request which are modifying the model and the new value needs to be communicated to the view.
lo.controller('listController', function ($scope, $http) {
$http.get('http://.......').success(function (data) {
$scope.lista = data;
$scope.$apply();
}).
error(function (data, status) {
$scope.lista = "Request failed";
$scope.$apply();
});
});
I just started with learning Angular and now i'm busy with an web application that shows some records i fetched from a JSON. The JSON looks like:
"results": [
{
"easy": false,
"id": 1,
"title": "title",
}
]
i am parsing that on this way (seems correct to me)
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.thing = data.results;
});
});
So now that i am in this JSON file i need to get the ID (in this case its 1) and with that ID i need to do a new request api.com/game/{id} to get more detailed information about the result from the first file.
What is the best way to do that?
$http.get('api.com/game/' + $scope.thing.id, function(...){ });
Point to note, you do not have to manually parse JSON with angular. It will do that for you. So data.results already has the object representing your response.
i think it is good idea if you do like this:
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('api_url').
success(function(data, status, headers, config) {
$scope.thing = data.results;
$scope.id=data.results[0].id;
gameInfo();
});
});
var gameInfo=function(){
$http.get('api.com/game/'+$scope.id).
success(function(data, status, headers, config) {
$scope.newThing = data;
});
}
Also take a look at ngResource which is a module that gives you more fine-grained control over HTTP requests. It does parameter replacement among other things (custom interceptors, etc.)
https://docs.angularjs.org/api/ngResource/service/$resource
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;
}
}