Load JSON in AngularJS App (loading google spreadsheet) - javascript

I am trying to load up a Google spreadsheet in my application, but I am not managing to make it work. I've tried different ways of accessing the tree structure (via the controller and/or via the html), but none of them worked.
Any idea what may be wrong?
Here is my controller:
app.controller('SuperCtrl', ['$scope', '$http', function($scope,$http) {
$http.get("https://spreadsheets.google.com/feeds/list/1lZWwacSVxTD_ciOsuNsrzeMTNAl0Dj8SOrbaMqPKM7U/od6/public/values?alt=json-in-script&callback=x")
.success(function(response) {
$scope.items = response;
});
}]);
And here is the HTML:
<ul ng-controller="SuperCtrl">
<li ng-repeat="item in items.feed.entry">
{{ item.title.type }}
</li>
</ul>

created a working plunkr for you
http://plnkr.co/edit/JfXrVDWacvjF2RzxP18g?p=preview
But here's also the meat of the solution:
app.controller('SuperCtrl', ['$scope', '$http', function($scope,$http) {
var url = 'https://spreadsheets.google.com/feeds/list/1lZWwacSVxTD_ciOsuNsrzeMTNAl0Dj8SOrbaMqPKM7U/od6/public/values?alt=json'
var parse = function(entry) {
var category = entry['gsx$category']['$t'];
var description = entry['gsx$description']['$t'];
var title = entry['gsx$title']['$t'];
var url = entry['gsx$url']['$t'];
var yo = entry['gsx$yo']['$t'];
return {
category: category,
description: description,
title: title,
url: url,
yo: yo
};
}
$http.get(url)
.success(function(response) {
var entries = response['feed']['entry'];
$scope.parsedEntries = [];
for (key in entries) {
var content = entries[key];
$scope.parsedEntries.push(parse(content));
}
});
}]);
First problem you were using the 'json in script' version of the API which is complicated and not what you want. Changed the API result to just be JSON.
Second problem is parsing the result, see my function there that converts the confusing google spreadsheet entries into nice readable JSON.
The example works - have a tinker. My advice is find something other than google spreadsheets to store your data.
It's funny, I actually built an app on top of google spreadsheets too (trackerkeeper.co), which is why I could help you. Not super proud of the engineering but it was kind of fun:
Good luck.

Here is a new working plunker. The problem was that it can't find the "yo" variable anymore.
var parse = function(entry) {
console.log(entry);
var category = entry['gsx$category']['$t'];
var description = entry['gsx$description']['$t'];
var title = entry['gsx$title']['$t'];
return {
category: category,
description: description,
title: title,
url: url
};
}
http://plnkr.co/edit/YwskJRuORJBjw4S9wU7V?p=preview

Related

Retrieving data from Firebase and repeating it in an Angular Controller

since I am new to the new SDK of Firebase (I have used a little bit of angularfire) I wanted to retrieve data and with angular to display it.
Here is what I have done so far:
var app = angular.module('dApp',[]);
app.controller('listingControler',['$scope', function($scope){
$scope.downloads = [];
var config = {
//removed config
};
firebase.initializeApp(config);
var leadsRef = database.ref('/');
leadsRef.on('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
$scope.downloads.push(childSnapshot.val());
});
return $scope.downloads;
});
}]);
View
<body ng-app="dApp">
<div ng-controller="listingControler">
<ul>
<li ng-repeat="d in downloads">{{d.email}}</li>
</ul>
</body>
Based on the comments you are getting the data (you said console allows you to view object properties). You need to specify the property names to get the string data. snapshot.val().firstName, for example.

AngularJS - updating the model shared by different controllers

I'm just starting with AngularJS, building my first test web app.
I have several controllers that share the same model.
This is my model:
uxctModule.factory ("ModelData", function () {
var data = {
param1: '',
param2: '',
param3: '',
[more params....]
}
return data
});
So this is an example of my controller
uxctModule.controller ('PageOne', function ($scope, ModelData){
$scope.data = ModelData;
[do things here]
});
I'm now trying to change the model by loading a string from a file, and I was expecting the app to update accordingly.
So in a controller I'm loading a file and trying to update the model:
uxctModule.controller ('NavigationController', function ($scope, ModelData) {
$scope.data = ModelData;
$scope.browsePressed = function (evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
console.log (contents);
console.log ("ModelData was " + ModelData.param1);
ModelData = JSON.parse(contents);
console.log ("ModelData is now " + ModelData.param1);
}
r.readAsText(f);
}
else {
alert("Failed to load file");
}
}
});
I've built a "debugger" div in the html to see the model:
<div id="debuggerBox" ng-controller="Debugger" width='300'>
<pre>{{data | json}}</pre>
</div>
...whose controller is simply:
uxctModule.controller ('Debugger', function ($scope, ModelData){
$scope.data = ModelData;
});
Now, when changing the model content loading the external file I can see on the console the right logs (values changed), but on the debugger box the Model object is still holding the old values.
As I said, I'm an AngularJS beginner, so maybe I'm doing something really wrong here. Any help is appreciated :)
The problem is you're replacing the whole object:
ModelData = JSON.parse(contents);
with this, the ModelData references another object but the original object is not modified.
You could fix this by copying field by field to the ModelData. Sample code:
var tempModelData = JSON.parse(contents);
ModelData.param1 = tempModelData.param1;
or you could try angular.copy:
angular.copy(JSON.parse(contents), ModelData);
Also try $scope.$apply to let angular aware of the changes:
$scope.$apply(function(){
angular.copy(JSON.parse(contents), ModelData);
});

ng-repeat rendering empty li elements

I am using ng-repeatto loop through the Rotten tomatoes api and display the movie title. This is the code I have
JS:
var app = angular.module('app', []);
app.controller('ApiCtrl', function($http){
var app = this;
var url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json"
var key = "?apikey=myKey"
$http.get(url+key)
.success(function(data) {
app.movies = data;
console.log(data);
})
})
HTML:
<li ng-repeat="movie in app.movies">
{{movie.title}}
</li>
</body>
This is outputting 3 blank li elements on the screen, if I call just {{movie}}then the entire object is outputted so I know the binding is correct.
An example of the JSON:
"movies": [
{
"id": "771315918",
"title": "Divergent",
}]
Where's your $scope?
Try something like:
var app = angular.module('app', []);
app.controller('ApiCtrl', function($scope, $http){
var url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json"
var key = "?apikey=myKey"
$scope.movies = $http.get(url+key);
I'm not sure if the above code will work of $http. My suggestion is that before trying to get the data from a server, get all the angular stuff working. For instance, define $scope.movies like this:
$scope .movies = [
{
"id": "771315918",
"title": "Divergent",
}
];
first and get that working.
The rotten tomatoes API has it's own movies key, so I think you need to do:
.success(function(data) {
app.movies = data.movies;
}
$scope and 'this' don't necessarily refer to the same thing. I would do
$scope.app = null;
//When the deferred object is returned
.success(function (data) {
$scope.app = data;
});
By using 'this' you are referring to the controller but is not accessible by the view. Here is another post that is really helpful:
'this' vs $scope in AngularJS controllers

http.get request not executing

I have been trying to figure out this problem for the last few hours and to the life of me I can't figure out what is wrong.
I have used both the debugging tools with netbeans and with chrome dev-tools and both seem to just skip it without trying to even execute it as I'm getting neither a error or success in fact I don't even get a xHR request sent off to collect the file.
Factory:
.factory('Stories', function($http) {
var factory = {};
var stories = [];
factory.status;
$http.get('../json/stories.json')
.success(function(data,status){
stories = data;
factory.status = status;
})
.error(function(data,status){
stories = data || "request faild";
factory.status = status;
});
factory.getStory = function() {
return stories;
};
})
This is only a section of the app but is contained so I don't think you will need the rest. if anyone could tell me what I am doing wrong that would be great Thanks in advance.
Fix it
For reference incase someone else comes accross a similar problems.
Check first:
check what is displaying the factory that the variables matchup
Make sure $http is being injected to param
set aliases for each of your params that are being injected
this was my final solution:
.factory('Stories', ['$http', function($http) {
var factory = {};
var stories = null;
stories = $http.get('./json/stories.json')
.success(function(data){
stories = data;
});
factory.getStory = function() {
return stories;
};
return factory;
}]);

Getting data from JSON url using angularJS

I am really new to using AngularJS and Javascript. I need to get the totalResults data from a JSON source that looks like this:
{
"queries": {
"request": [
{
"totalResults": "51"
}
]
}
}
Once I get the data, I need it to show up in a list using AngularJS. I have tried really hard using .ajax and .getJSON, but I am unable to get either of them to work, given my complete lack of knowledge on using JavaScript. I really appreciate your help! My AngularJS looks like this:
function MyController($scope){
$scope.url = "https://www.googleapis.com/customsearch/v1?key=[MYKEY]&cx=[MYSECRETKEY]&q=flowers&alt=json&fields=queries(request(totalResults))";
$scope.newMessage = "";
$scope.messages = ["Steve Jobs - 515,000,000 results"];
$scope.add = function(){
$scope.messages.push($scope.newMessage);
};
}
}
In the HTML part, I have this:
<input type="text" ng-model="newMessage">
<input type="submit" ng-click="add()" value="Click to find out!">
When the user clicks the button, I want the url to be called and the $scope.newMessage should be the value in totalResults. Thanks for your help!
You can use $http service: Documentation
So you can:
$scope.add = function(){
$http.get($scope.url).then(function(response) {
$scope.newMessage = response.data.queries.request.totalResults;
$scope.messages.push($scope.newMessage);
});
};
Read a little in $http service provided by AngularJS
here is the hint to the code that you would use
$scope.add = function(){
$http.get(url).then(function(response){
queries = response.queries;
$scope.newMessage = queries.request.totalResults;
})
}
See http://plnkr.co/edit/nZkYsxLHLvf3SZNiJKic?p=info
Following your link, I just found one error:
var x = searchResults.split('.');
don't have function split() if i replace: x = "abc"
the result :
Steve Jobs - 515,000,000 results
- a.b results
dsgdfg - a.b results

Categories