Angularjs not storing variable to $scope after AJAX call within $http.get request

FugueWeb picture FugueWeb · Nov 19, 2014 · Viewed 7.5k times · Source

I'm using angularjs and I can't get the following controller to save to a $scope variable the data returned from an AJAX request to Flickr. The $http.get makes a call to a locally saved json file. Upon success, it uses the json returned in success() to determine the appropriate url for the AJAX call to the Flickr API. Upon success of that call, I log the data to the console. So far so good, it returns an array of three objects. However, I'm trying to set that array to a $scope variable ($scope.photos) so I can iterate over it my view template. However, when I try outputing {{photos}} in the html there is nothing. I suspect this is a promise issue, and the template is rendering before the AJAX returns the data from Flickr, but I've been pouring over the docs with no success (looked at $q a little). I'm somewhat new to Angular and would appreciate your insight. Thanks!

artistControllers.controller('PhotoController', ['$scope', '$http', '$routeParams', '$q', function ($scope, $http, $routeParams, $q){
  $http.get('js/data.json').success(function(data){
    $scope.artists = data;
    $.ajax({
         type : "GET",
         dataType : "jsonp",
         url : $scope.artists[$routeParams.itemId].flickr,
         success: function(flickr){
            $scope.photos = flickr.items;
            console.log($scope.photos);
         }
    }); 
  });
}]);

Answer

Brian Lewis picture Brian Lewis · Nov 19, 2014

Don't use jQuery.ajax. Angular's $http can do JSONP too. You can read more about here.

artistControllers.controller('PhotoController', ['$scope', '$http', '$routeParams', '$q', function ($scope, $http, $routeParams, $q){
  $http.get('js/data.json').success(function(data){
    $scope.artists = data;
    $http.jsonp($scope.artists[$routeParams.itemId].flickr).success(function(data){
        $scope.photos = flickr.items;
        console.log($scope.photos);
    });
  });
}]);