binhxn89 binhxn89 - 5 months ago 17
AngularJS Question

ng-repeat not iterating through list of images in JSON

I'm quite new to Angular and am having trouble using the $http service to make a GET request for images in JSON (just a plain array of images). For every image, I want to repeat that and add them into my ng-src. I'm trying to achieve a layout similar to Instagram.

So I think the $http.get part is correct where I store it into $scope.imageUrls, and from there I iterate through it using ng-repeat. Then from there, for each iteration, I plug that into ng-src in my img tag and I just don't know how to debug from there.

HTML:

<div class="posts" ng-controller="PostController">
<div class="post" ng-repeat="imageUrl in imageUrls">
<img class="photo" ng-src="{{imageUrl}}" />
<div class="post-box">
<div><span class="likes"> # </span> Likes</div>
</div>
</div>
</div>


JS:

var app = angular.module('instagram', []);

app.controller('PostController', ['$scope', '$http', function($scope, $http) {

$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
.then(function (data) {
$scope.imageUrls = data;

console.log($scope.imageUrls);
});
}]);


I tried used console.log to check for errors, but the data seems to be there. Is it just returning the block of data rather than each element/image in the JSON?

Checking the console: console.log($scope.imageUrls)

I also tried using {{imageUrl.url}} as ng-src but that seemed to trigger errors as well. I set up a Plnkr:
http://plnkr.co/edit/yQpCIRp9FHdDHTMA1HCL?p=preview

This has been bugging me for awhile, so if you can help, thanks!

Answer

I update your plunker http://plnkr.co/edit/hNn1YdVh8w7l3dEgh3LU?p=preview:

In $http you get a responsa that contains more informations that only data. To get data you must do it :

$http.get('https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json')
    .then(function (response) {
      $scope.imageUrls = response.data;

      console.log($scope.imageUrls); 
    });

And in ng-repeat you must add track by argument because image can be duplicate