Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 434
Prajoth Avatar asked Jan 22 '13 19:01

Prajoth


3 Answers

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);
  });
};
like image 177
Valentyn Shybanov Avatar answered Nov 18 '22 23:11

Valentyn Shybanov


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;
    })
}
like image 39
Arshabh Agarwal Avatar answered Nov 18 '22 23:11

Arshabh Agarwal


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

like image 31
Quỳnh MSO Avatar answered Nov 19 '22 01:11

Quỳnh MSO