Reputation: 434
I am trying to iterate through an array of usernames and add the resulting JSONP requests to an array that can be displayed using AngularJS. As follows:
HTML SECTION
<div id = "displayUL" ng-controller="userController">
<ul>
<li ng-repeat="user in results">{{user.user}}<img ng-src="{{user.logo}}">{{user.etcetera}}</li>
</ul>
</div>
JAVASCRIPT SECTION
var app = angular.module('userAPI', []);
app.controller('userController', function($scope,$http){
//Our user name array
$scope.inputUsers= ["userA", "userB", "userC"];
$scope.results = [];
//Loop through each user
$.each($scope.inputUsers,function(key,value){
var currentUserData = {};
currentUserData.user = value;
//URL Request - defined elsewhere with callback for JSONP
var currentURL = streamURL + value + callbackPostfix;
$.getJSON(currentURL, function(data){
//Update temp obj with current data results
currentUserData.found = data.found
currentUserData.logo = data.logo;
...
currentUserData.ecetera = data.ecetera;
//Update results array with current data obj
$scope.results.push(currentUserData);
});
});
When this runs, the results array is empty. Does the JSONP callback fire before the Angular has a chance to update?
Upvotes: 0
Views: 84
Reputation: 171679
Assuming the url and response are correct, your problem is using $.getJSON
which isn't part of angular.
Whenever you make changes to the scope with code that is outside of angular core you need to tell angular to run a digest to update view with scope changes using $scope.$apply()
.
I would suggest you convert to using $http.jsonp
instead which will handle digests internally.
$.getJSON(currentURL, function(data){
//Update temp obj with current data results
currentUserData.found = data.found
currentUserData.logo = data.logo;
...
currentUserData.ecetera = data.ecetera;
//Update results array with current data obj
$scope.results.push(currentUserData);
// now time for a digest to update view
$scope.$apply();
});
Upvotes: 3