user3438917 user3438917 - 3 months ago 20
JSON Question

Grabbing key:values from JSON object in Angular

I am trying to loop through the returned JSON and display images based on the results. I am able to pull the feed, but not sure where I'm going wrong on grabbing the

poster_path
from the results and appending to an
<img ng-src="">
path.

The JSON:

results: [
{
poster_path: "/title-of-image.jpg",
overview: "description of movie",
release_date: "2016-08-03",
id: 297761,
original_language: "en",
title: "Movie title",
popularity: 44.788935,
}
}


I'm looping through the object and able to view the results in the console, but can't grab the data correctly:

var myapp = angular.module('myapp', []);
myapp.controller('demoController', function($scope, $http){
$http.get("http://api.themoviedb.org/3/movie/now_playing?api_key=ebea8cfca72fdff8d2624ad7bbf78e4c")
.success(function(response) {
console.log(response);
$scope.results = response;
});
});

<div class="container" ng-repeat="result in results">
<div class="col-lg-12">
<img class="col-lg-3 col-md-4 col-xs-12 thumbnail" ng-src="http://image.tmdb.org/t/p/w342" + {{result.poster_path}}></a>
</div>
</div>


This is what I'm seeing in the console:

Object {page: 1, results: Array[20], dates: Object, total_pages: 33, total_results: 654}

GET http://image.tmdb.org/t/p/w342 400 (Bad Request)

Results array expanded:
enter image description here

Answer

If you look at the output of your console.log(response), you will see that the data you want is actually in a property called results.

{page: 1, results: Array[20], dates: Object, total_pages: 33, total_results: 654}

So the data you want to look is actually response.results. Does that make sense? With that in mind, we want to have the following html snippet.

<div class="container" ng-repeat="items in results">
      <img ng-src="http://www.source-to-image" + {{items.poster_path}}>
</div>

and then the following controller:

var movieapp = angular.module('movieapp', []);
myapp.controller('movieController', function($scope, $http){
  $http.get("http://www.url-to-source")
    .success(function(response) {
      console.log(response);
      $scope.results = response.results;
    });
});

I can't tell what's in each poster_path, so let me know if this works.