Retrieving data using JSON url using angularJS

I am really new to using AngularJS and Javascript. I need to get totalResults data from a JSON source that looks like this:

{ "queries": { "request": [ { "totalResults": "51" } ] } } 

As soon as I get the data, I need it to appear in the list using AngularJS. I tried hard using .ajax and .getJSON, but I can't get them to work, given my complete knowledge of 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 the following:

 <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 value of $scope.newMessage should be the value in totalResults. Thank you for your help!

+6
source share
3 answers

You can use the $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); }); }; 
+15
source

Read a little about the $ http service provided by AngularJS

here is a hint for the code you would use

 $scope.add = function(){ $http.get(url).then(function(response){ queries = response.queries; $scope.newMessage = queries.request.totalResults; }) } 
+1
source

See http://plnkr.co/edit/nZkYsxLHLvf3SZNiJKic?p=info

Following your link, I just found one error:

 var x = searchResults.split('.'); 

don't have split () functions if I replace: x = "abc"

result: Steve Jobs - 515 million results - Results ab Results dsgdfg - ab

+1
source

All Articles