0

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?

1 Answer 1

3

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();
       });
Sign up to request clarification or add additional context in comments.

2 Comments

That works. Tried with the $http.jsonp but I got the XML Cross-Origin policy error which is why I'm using $.getJSON because the site has JSONP Callback allowance.
just means you aren't using $http.jsonp properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.