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
Related
As the title says, I have a problem with reference switching.
My html:
div ng-repeat="data in parseurl">
{{data.url}}
</div>
In my JS code, I'm trying to do two things. The first step is to grab the data off a server and put it into an array (called allsongs). Afterwards, I parse the data and put it into another array (parseurl).
var app = angular.module("write", []);
app.controller("Ctrl", ['$scope', '$http', function($scope, $http){
$scope.allsongs = [];
$scope.parseurl = [];
$scope.getstuff = function(){
$http.get("my link here").then(function(response){
$scope.allsongs = response.data;
}); //step one -> this works!
$scope.parser(); //step two
};
$scope.parser = function()
{
for(i=0;i<$scope.allsongs.length;i++) {
for(var key in $scope.allsongs[i]) {
var value = $scope.allsongs[i][key];
var object = {Url : value.Url}; //this does contain the correct info I want
$scope.parseurl.push(object);
}
$scope.getstuff();
}]);
So what is happening is that, if I ng-repeat on allsongs, then I do get a bunch of un-parsed urls. But if I ng-repeat on parseurl, then I get nothing. Obviously the reference isn't changing, but how can I do it?
$scope.parser() needs to be called after the data was recived. Put it into your promise callback function like in the following example. Please note that $http is an asynchronous function. In that way $scope.parser() was executed before your request has been finished.
$scope.getstuff = function(){
$http.get("my link here").then(function(response){
$scope.allsongs = response.data;
$scope.parser();
});
};
I am trying to work with AngularJS and a Web API written in VB.NET (Doing this for my internship).
I have my angularApp defined, same for my controller and factory.
I'm also working with the routing from Angular and this works perfectly.
The issue I'm dealing with is that my factory isn't activated or isn't working.
Please take a look at the code below:
My AngularApp.js
var angularApp = angular.module('AngularApp', ['ngRoute']);
angularApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/ExpenseOverview', {
controller: 'ExpenseController',
templateUrl: 'Views/ExpenseOverview.aspx'
})
.when('/AddExpense',
{
controller: 'ExpenseController',
templateUrl: 'Views/AddExpense.aspx'
})
.otherwise({ redirectTo: '/ExpenseOverview' });
}]);
My ExpenseController:
angular.module("AngularApp").controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, ExpenseFactory) {
//variabelen
$scope.expenses = [];
$scope.id = 0;
$scope.date = "";
$scope.type = "";
$scope.title = "";
$scope.project = "";
$scope.status = "";
$scope.img = "";
var shown = false;
var dataURL = "";
ExpenseFactory.getList($scope);
}]);
So far my controller isn't doing much more other than retrieving a list of data from the database through the web API.
My ExpenseFactory.js
angular.module("AngularApp").factory("ExpenseFactory", ["$http", function ($http) {
alert("test factory");
var factory = {};
//lijst van expenses ophalen
factory.getList = function ($scope) {
$http.post("/api/Expense/List")
.success(function(data) {
if (data === undefined || data == "") {
data = [];
}
$scope.expenses = data;
$scope.id = $scope.expenses[$scope.expenses.length - 1].Id + 1;
})
.error(function() {
alert("Er is een fout opgetreden");
});
};
factory.saveList = function(expenseList) {
$http.post("/api/Expense/SaveList", { 'expenses': expenseList })
.success(function() {
alert("Expenses have been saved succesfully!");
})
.error(function() {
alert("Something went wrong while saving the expenses");
});
};
return factory;
}]);
As you can see, I have put an alert as the first line of code in the factory. This alert isn't even popping up, which means the factory isn't activating/working.
What is failing in this code?
EDIT
I updated my code to the current version with all the comments about things that might be interfering with the code. I can confirm that none of this was working, so the error is occuring somewhere else.
Another note: I'm working with Visual Studio 2012, if this might have something to do with it, please do elaborate how I can fix this shenannigans.
You missed to return $http promise from factory methods
factory.getList = function ($scope) {
return $http.post("/api/Expense/List")
.success(function(data) {
if (data === undefined || data == "") {
data = [];
}
$scope.expenses = data;
$scope.id = $scope.expenses[$scope.expenses.length - 1].Id + 1;
})
.error(function() {
alert("Er is een fout opgetreden");
});
};
factory.saveList = function(expenseList) {
return $http.post("/api/Expense/SaveList", { 'expenses': expenseList })
.success(function() {
alert("Expenses have been saved succesfully!");
})
.error(function() {
alert("Something went wrong while saving the expenses");
});
};
Rather than passing whole scope, you should create one model object like $scope.model = {} and that will hold the all value of ng-model (scope variables) don't pass whole scope to factory, Pass only relevant data to service method.
As the app, controller and factory are in different files, it's better to avoid referencing the module using angularApp.
Instead use the following syntax:
angular.module('AngularApp').factory("ExpenseFactory", ["$http", function ($http) {
Here,
angular.module('AngularApp')
Means you're getting the module.
If you're going to use var angularApp, you're actually polluting the global namespace with your variable name.
Also if by chance in some other library code, someone reassigns it to something else then your entire application will break.
for example:
in another file, `angularApp = alert;`
And one more thing,
In your controller:
angularApp.controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, expenseFactory) {
You have a typo in expenseFactory as it must be ExpenseFactory
angularApp.controller("ExpenseController", ["$scope", "ExpenseFactory", function ($scope, ExpenseFactory) {
Thank you #mohamedrias for helping me find to solution.
It was indeed because of the URL Path that was invalid.
Because of the view that couldn't be loaded, the factory was crashing alongside it.
I don't know how this happened, but it's fixed now!
All the code was correct, except for a reference to an invalid URL path for my views.
Thanks for all the help and comments, I'll keep everything in mind for the upcoming parts of my project.
StackOverflow is awesome!
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
I have the following controller in my application, but there is some strange behaviour that I cannot explain. I've numbered two of the lines to help with the description, they don't both exist at the same time in the live code.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
var cachedMovieList = [];
//Controller for movie list
app.controller('MovieListController', ['$http', function($http){
var mlc = this; //needed for the $http request
this.movies = cachedMovieList;
this.loaded = false;
this.error = false;
if(this.movies.length == 0) {
console.log("Grabbing new movie list from DB");
$http.get('data/movies.json').success(function(data){
mlc.movies = data;
mlc.loaded = true;
cachedMovieList = data; //(1)
}).error(function(data){
mlc.error = true;
});
cachedMovieList = this.movies; //(2)
} else {
this.loaded = true;
}
}]);
With the code as above with line (1) present and line (2) not present, I am able to cache the result so that when I flick between pages I don't need to constantly re-get the data.
However if I remove line (1) and insert line (2), the variable "cachedMovieList" is never populated. I would expect it to be based on the fact that "mlc.movies" was assigned to... but I cannot understand why this is the case?
Any advice welcome.
Implement a factory that retrieves the data. Use angular.copy to preserve the array reference when the data returns from the $http call.
var app = angular.module('movieListings', ['ngResource', 'ngRoute', 'ui.bootstrap', 'ng']);
app.factory('movies', function($http) {
var movies = {
data: [],
loaded: false,
error: false
};
$http.get('data/movies.json').success(function(data){
angular.copy(data, movies.data);
movies.loaded = true;
}).error(function(data){
movies.error = true;
});
return movies;
});
Inject the factory into your controller:
//Controller for movie list
app.controller('MovieListController', ['$scope','movies', function($scope, movies){
this.movies = movies;
}]);
Factories (like services) are singletons. They are initialized once, and cached for the entire lifetime of the SPA.
Use the controller in the view:
<div ng-controller="MovieListController as ctrl">
<div ng-show="!ctrl.movies.loaded"> Loading... </div>
<ul>
<li ng-repeat="movie in ctrl.movies.data">
{{ movie.name }}
</li>
</ul>
</div>
If I've understood this correct, you're entering the if condition only when this.movies.length == 0. In such a case, this.movies will be null, so cachedMovieList would get populated with a null value.
Because (2) probably gets executed first before the $http.get() request is finished. $http.get() is an AJAX request.
If you want to cache, you might want to use $cacheFactory instead :)
I believe you are mistaking the live updation of values that happens in view to live updation that would happen with variable assignments. Your line 2 will set cachedMovieList to [] initially. I believe that is quite obvious. But you think that since callback updates this.movies that change would cascade to cachedMovieList. That won't happen as you are re-assigning the mlc.movies variable that means it refer to new variable instead of modifying existing value.
If you really want to make you logic work, please update mlc.movies variables like following
mlc.length = 0 // Empty the array
mlc.push.apply(mlc, data);
Please check following answer for more information
How do I empty an array in JavaScript?
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