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).
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:
jsonp
instead of get
alt=json-in-script
instead of alt=json
(note this may be different based on API docs)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.