How would I access this JSON data in AngularJS? - json

I am trying to learn how to load JSON with Angular. I'm a beginner with both topics, and am stuck on some really beginner topics.
I have a JSON file called food.json. It has structure like this:
[
{"uid":"55","title":"Nussbrot","code":"U VP 0000030","unit":[{"title":""}],"unitgram":"0","unitgram_second":"0","sorting":"0"},
{"uid":"58","title":"Walnu\u00dfbrot","code":"X 39 2000002","unit":[{"title":"Scheiben"}],"unitgram":"45","unitgram_second":"0","sorting":"0"}
]
Following instructions from http://toddmotto.com/ultimate-guide-to-learning-angular-js-in-one-day/, I have a controller like this:
myApp.controller('EmailsCtrl', ['$scope', function ($scope) {
$scope.foodlist = {};
$scope.foodlist.foodtitle = '';
$http({
method: 'GET',
url: 'food.json'
})
.success(function (data, status, headers, config) {
$scope.foodlist = data.; //I don't know what to call here as my data elements have no names?
})
.error(function (data, status, headers, config) {
//error
});
}]);
The first point I am stuck in is, how do I assign data to my ´$scope.foodlist´ if the JSON objects have no names?
I've built a Plunkr of my not-working attempts so far, and would appreciate any guidance in a) reading in the JSON and b) assigning the JSON data to values in controller.

ng-repeat in your case will iterate the array of objects in your data
You just need to use :
<li ng-repeat="food in foodlist">
Then on each pass of the loop, angular will reference the current object in array to produce output like {{ food.title }}
I updated your demo here
Edit Strongly suggest you go through the tutorial on angular docs site step by step

The first problem is in the controller definition: You are trying to reference $http but you are not passing it in.
myApp.controller('EmailsCtrl', ['$scope', '$http', function ($scope, $http) {
Then on success your data parameter is your foodlist:
.success(function (data, status, headers, config) { $scope.foodlist = data; })
Finally, in your html, ng-repeat should be like this:
ng-repeat="food in foodlist"

Related

loading multiple JSON files in AngularJS

I have two different JSON files and they have the same attributes in them. I'm able to load them by using two promises in my service but when I go in my HTML and try to display my data they display the same thing.
This is my service:
$http.get("data.json");
//User JSON api
$http.get("data1.json")
.then(function (response) {
dataRecievedCallback(response.data);
}
Should I assign my $http.get to a variable, if yes How can I do that and do I need to change anything in my controller?
I haven't been coding for long and I'm new to angular so all the help is appreciated.
$http.get("data.json")
.then(function (response) {
$scope.foo = response.data;
}
$http.get("data1.json")
.then(function (response) {
$scope.bar = response.data;
}
Not sure about your "dataRecievedCallback()" function, if your function set the data into the same variable, the second $http call will overwrite the first one.

Accessing JSON data from Neo4j REST response in Angularjs

I'm a newbie with rest and angular, so my hope answer to my question is super easy.
I'm having problem working with JSON response I get from new Neo4j post transaction/commit query.
I want to access response data for each item I have in the response. I've searched how others handle this, but have found no same cases. I think I do not parse the response at all, and can not access the specific row.
Here is my code, that just prints all the json.
JS controller
function restcall($scope, $http) {
var call = '{ "statements" : [ { "statement" : "MATCH (n:Cars) RETURN n ORDER BY n.initRank DESC LIMIT 10" } ] }';
$http({
method: 'POST',
url: 'http://myserver:7474/db/data/transaction/commit',
data: call,
})
.success(function (data, status) {
$scope.status = status;
$scope.response = data.results;
})
.error(function (data, status) {
$scope.response = data || "Request failed";
$scope.status = status;
})
};
HTML that just prints out complete response
<section ng-controller="restcall">
<h2>{{status}}</h2>
</br></br>
<h3>{{response}}</h3>
</section>
And most importantly the JSON response I get
{
"results":[{
"columns":[
"n"
],
"data":[
{"row":[{"name":"Car1","initRank":"..."}]},
{"row":[{"name":"Car2","initRank":"..."}]},
{"row":[{"name":"Car3","initRank":"..."}]},
{"row":[{"name":"Car4","initRank":"..."}]},
{"row":[{"name":"Car5","initRank":"..."}]},
{"row":[{"name":"Car6","initRank":"..."}]}]
}],
"errors":[]
}
So basically now I just print out in html my json response.
Now, how do I access individual rows to get i.e. Car3 properties??
I tried the data.results[0][0].data... and also to parse my string, but when I add next .data it just doesn't show a thing, same thing with parsing.. Can someone help please.
Based on that JSON response, you would use data.results[0].data[2].row[0].initRank to access the "initRank" of Car3. You shouldn't need to do any extra parsing of the response. It should already be an object in your callback.

Trouble with loading json files into template.html using angular factories

I am trying to understand how to use factories and struggling to understand a few things.
I want to load json file into template but I am hitting the wall
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
myApp.factory('Tester', function($resource) {
return $resource('users.json');
});
myApp.controller('PersonCtrl', function ($scope, Tester, getUsersFactory) {
// Teens are from static json file
$scope.users = Tester.query();
// Adults are from REST API
$scope.teens = getUsersFactory.query();
});
If you will have look in my example you will see that I am trying to load from users.json file content to main.html
I would like to be able to load multiple json files into main.html
PLUNKER example here
Could you please advice me with example how to do this correctly.
You need to change your getUsersFactory factory, because you don't have there $scope:
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(searchStr, callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ searchStr}).success(callback);
}
}
}]);
As you can see, i added one more parameter - searchStr.
You need to call function getUsers() of your factory getUsersFactory. Actually problem is next: function query() is not defined in your factory getUsersFactory.
Actually seems it works even if call $scope.teens = getUsersFactory.getUsers(); - without params.
So, answer to your question - use function of factory which you defined: getUsersFactory.getUsers()
Changed plunk: http://plnkr.co/edit/xIzd8Zyg0hzMgbPCzEfj?p=preview

Angularjs $resource and $http synchronous call?

I want write two services one with a $http.get method and one with $resource
This service should receive a Json Object and looks like this, at the moment this code is direct in my controller and not in a service:
var csvPromise= $http.get(base_url + 'DataSource/1').success(function(data) {
$scope.data4=JSON.stringify(data);
});
The problem is, I want save received data in $scope.data4 and I want use this data after the $http.get call but the value is empty.
Direct after this call there is and Object that needs this value:
new myObject($scope.data4)
so myObject must wait so long until the data has arrived.
or can I make a synchronous call with $http or $resource ?
How can i do this ? I have found so many examples with promise and .then but nothing has worked for me.
EDIT: I have now written a service but it didn`t work:
var test=angular.module('myApp.getCSV', ['ngResource']);
test.factory('getCSV',function($log, $http,$q, $resource){
return {
getData: function (id) {
var csvPromise= $http.get(base_url +'DataSource/'+id)
.success(function(data) {
return data;
});
return csvPromise;
}
}
});
and then in my controller I call this:
getCSV.getData(1).then(function(theData){
$scope.data4=JSON.stringify(theData);
new myObject( $scope.data4); });
but this did not work. I thought if the $http.get receives the data then the then Function is called.
I don't believe you can do synchronous calls. That said, you have at least two options:
1) Pass in the data using the $routeProvider resolve feature. From the documentation:
An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected
An example on how to use this:
$routeProvider
.when('/your/path', {
templateUrl: '/app/yourtemplate.html',
controller: 'yourController',
resolve: {
data: ['$route', '$http', function($route, $http) {
return $http.get(base_url +'DataSource/1');
}]
}
})
And then in your controller:
app.controller('yourController', ['$scope', 'data', function($scope, data) {
$scope.data4 = JSON.stringufy(data);
var yourObj = new myObject($scope.data4);
}]);
2) The second option is to use promises and only instantiate your new myObject($scope.data4) once the promise successfully completes.
Your code needs to be changed just a bit:
$scope.data4 = '';
var csvPromise= $http.get(base_url +'DataSource/1');
csvPromise.then(function(data){
$scope.data4 = JSON.stringify(data);
}, function(data){
//error handling should go here
window.alert(data);
});
This should give you what it sounds to me like you need.
As i know, there's no way to sync~ call the http or resource. They're hard coded on AngularJS core file :
xhr.open(method, url, true);
And you don't want to hurt your users too by blocking the browser wait the data arrived. You'll better show how you make the nothing has worked for me so we can start working to fix it.
Have you try call new myObject($scope.data4) inside success method?
$http.get(...).success(function(data){
$scope.data4 = JSON.stringify(data); // I've no idea why do you need this.
var stuff = new myObject($scope.data4); // THis is now your.
});

Get JSON data with AngularJS and add methods on the returning object

I need to get some JSON data from the server with Angular. Let's say the user data. I created a service like that:
app.service('User', function($http) {
retrun $http({method: 'GET', url:'/current_user'});
});
And in my controller:
app.controller('SomeCtrl', function($scope, User) {
User.success(function(data) {
$scope.user = data;
});
});
That works just fine but what if I want to add some methods to the user? For instance in the view I would like to do {{user.isAdmin()}}. Is it the correct approach? Where can I add those methods?
If you wanted your service to always return an object with this method, do something like this:
app.service('User', function($http) {
return $http({method: 'GET', url:'/current_user'}).
then(function(response) {
response.data.isAdmin = function() { return true; };
return response.data;
});
});
Now any future code that references this promise and uses .then() will retrieve the new object. Take a look at the promise documentation for more information.
http://docs.angularjs.org/api/ng.$q
Keep in mind by using 'then' on an httpPromise it will be converted to a normal promise. You no longer have the convenience methods 'success' and 'error'.
It may be better practice to create a class for the object you are returning with a constructor function which takes the data object and assigns appropriate properties (or extends the instance). This way you can simply do something like
return new User(val);
And you will get all of the methods you want (with a prototype, etc).
You can do this in a few ways in the service you created:
Start using $resource and use a transform on the response:
http://jsfiddle.net/roadprophet/prtAP/
...
transformResponse: function (data, headers) {
data = {};
data.coolThing = 'BOOM-SHAKA-LAKA';
return data;
}
...
I recommend this method because it scales cleaner due to the use of $resource.
Setup a transformResponse with $http:
http://jsfiddle.net/roadprophet/bPfcz/
Use your own promise that resolves after the get promise resolves but with the mapped data. This is probably the most manual way to handle it since it requires you to manage multiple promises.