0

How do I parse in $ from JSON HTTP responses in AngularJS?

Trying to grab YouTube search results without JQuery:

$http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published')
    .success(function (data) {
         $scope.video_list = data;
    })
    .error(function (data) {
         $scope.video_list = data;
});

No error response from that one, get an Object when consoling it; but cannot query within it.

$scope.video_list_fun = function () {
    $http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published').then(function (response) {
          $scope.video_list = response.data;
    });
};

Same here, have tried with , chained else also.

$scope.video_list = (httpGet('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published'
                     )); // HttpGet from http://stackoverflow.com/a/4033310/587021

This works, but when I parse it, e.g.: with JSON.parse; AngularJS gets rid of all the keys with $ in them.


Should note that I have tried with their other API, but wasn't able to get the same results (and can't include their useful args for published date and quality; because it's broken).

A T
  • 13,008
  • 21
  • 97
  • 158
  • 1
    Checking out [this github issue](https://github.com/angular/angular.js/issues/1463), there doesn't appear to be a nice solution... – A T Jul 07 '13 at 18:58

1 Answers1

2

It looks like a cross domain restriction. See if using $http.jsonp will work for you.

Check out the "Using the Data API with JavaScript" in the YouTube documentation where it states you will need to use alt=json-in-script as well as the callback parameter.

So instead of accessing:

$http.get('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json&orderby=published')

You will access:

 $http.jsonp('http://gdata.youtube.com/feeds/api/videos/-/chocolate?alt=json-in-script&orderby=published&callback=JSON_CALLBACK')

Note the differences:

  1. Use jsonp instead of get
  2. Use alt=json-in-script instead of alt=json (note this may be different based on API docs)
  3. Add callback=JSON_CALLBACK (note this may be different based on API docs but AngularJS is looking for JSON_CALLBACK in the response.

Check out this fiddle to see a working version (compare with this fiddle based on the original code).

Also check out this wiki article for more info on JSONP.

Gloopy
  • 37,767
  • 15
  • 103
  • 71
  • Hmm, I was trying with `jsonp` before using the `success` promise syntax; didn't try with then or the `JSON_CALLBACK` syntax, so thanks :D – A T Jul 07 '13 at 19:43
  • I have tried both syntaxes (with exact same code; char for char), but neither seem to work for me. I have tried from localhost and on my heroku app. – A T Jul 07 '13 at 20:23
  • What are you trying to do with the data? I modified the first fiddle [here](http://jsfiddle.net/3JWxQ/1/) to show some video titles does it work for you? – Gloopy Jul 07 '13 at 20:43