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
Related
I am new to Angular, but managed to make an Ajax-call and print out users from Random User Generator API in a list view.
Now I want to make a detailed view while clicked on a user.
In my HTML I make a function call: fetchInfoById(user.id.value)
In my script the function:
$scope.fetchInfoById = function(info_id) {
$http.get("https://randomuser.me/api/?id.value="+info_id)
//also tried: $http.get("https://randomuser.me/api/?id/value="+info_id)
.success(function(data) {
$scope.oneUserResult = data.results;
});
}
It does give me a user to a detail view, but not the chosen one. What am I doing wrong?
Thanks for your good suggestions.
I know it is a random generator, but setting parameters for the request to: "seed=...", the same persons is displayed on each listview request:
$http.get('https://randomuser.me/api/?results=15&seed=abc&inc=gender,name,location,email,dob,phone,cell,id,picture,info,nat&nat=gb')
.success(function(response){
$scope.userResult = response.results;
});
Then I fetched the id for each person and passed in as a parameter to the function call for the request for the detail view.
I tried with console.log() to make sure I passed in the right value for the detail view request and then even hardcoded the
parameter for the request ie:
$scope.getInfoById = function(info_id) {
console.log("from HTML: "+info_id.value ); // = JK 00 46 67
$http.get("https://randomuser.me/api/?id="+'JK 00 46 67 H') ...
The jason data behind the API is formatted like this for the id-property:
{
"results": [
{
"id": {
"name": "BSN",
"value": "04242023"
},...
I still haven't figured out how to get the one user by id. Getting different users all the time, even with hard coded id...
Instead of making the second request my solution was to a pass the "clicked user" as a parameter for the detailed view.
Change your code to this:
$scope.fetchInfoById = function(info_id) {
$http.get("https://randomuser.me/api/?id="+info_id)
//also tried: $http.get("https://randomuser.me/api/?id/value="+info_id)
.success(function(data) {
$scope.oneUserResult = data.results;
});
}
Also, make sure you are passing in the correct value to this function.
Fetch a list of users from API call "https://randomuser.me/api/?results=5".
$scope.getAllUsers= function(resultCount) {
$http.get("https://randomuser.me/api/?results="+resultCount)
.success(function(data) {
$scope.users= data.results;
});
Display them on the screen.
On click of one record fetch details for that particular record from users list fetched earlier.
$scope.getUserById= function(userId) {
return $scope.users.filter(function(user) {
return user.id.value=== userId;
})[0]; // apply necessary null / undefined checks wherever required.
}
another way using ng-model:
$scope.user = {};
$scope.fetchInfoById = function() {
$http.get("https://randomuser.me/api/?id="$scope.user.id)
.success(function(data) {
$scope.oneUserResult = data.results;
});
}
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 new for Meteor.js and javascript. I faced a weird question when I tried to pass router parameter.
My code like:
Router.route('/ends/:keyword', function () {
this.render('navbar', {
to:"navbar"
});
this.render('search_list', {
to: "search_list",
data:function(){
var keywords = this.params.keyword;
var filtered = Websites.find({ "description": { $regex: keywords }});
return filtered;
}
});
},{ name: 'search.show' });
Template.search_form.events({
"submit .js-search-website-form":function(event){
var keyword = event.target.keywords.value;
Router.go('search.show',{ keyword:keyword });
}
});
For example when I submit course, I expected the url change to /ends/course, but it shows as /ends/?.
However if I type /ends/course directly in address bar, it works properly. I would be very thankful if someone can give me some clues. I spent the whole day on it, but no solution.
Try this
Router.go('search.show',{keyword:keyword},{});
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);
});
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