vendredi 2 octobre 2020

$scope array not updating in Angular

I have an array of movies defined as a $scope variable, $scope.moviesList. I initialized all of the imageSrc fields for each object in the array to '' (empty string) and want to update this field for each object using the following function (the API key has been blanked out):

//loadMoviePosters calls the movie API for each movie in the moviesList array
//and sets the imageSrc field to the Poster link returned
$scope.loadMoviePosters = function(){
    for(var i = 0; i < $scope.moviesList.length; i++) {
        var movie = $scope.moviesList[i];
        $http({
            method: 'GET',
            url: "https://www.omdbapi.com/?t=" + movie.title + "&apikey=XXXXXXX"
        }).then(function success(response) {
            if (response.data.Poster != "N/A") {
                movie.imageSrc = response.data.Poster;
            }
            else {
                movie.imageSrc = '';
            }
            $scope.moviesList[i] = movie;
            //alert($scope.moviesList[i].imageSrc);
        },
        function error(respnonse) {
            //do nothing
        })
    }
    alert($scope.moviesList[0].imageSrc);
}

When I uncomment the alert inside of the for loop, it displays the image link for each object in the array, but the alert outside of the for loop always displays an empty string. It looks like the $scope.moviesList array is not actually being updated in this function.

In my HTML, I have the following code which I want to display the poster for each movie after this function updates the $scope array:

<div ng-repeat = "movie in moviesList">
                <img ng-src = "" />
                <p></p>
</div>

Does anyone know how I can get the loadMoviePosters function to actually update the $scope.moviesList array? And then how can I get these images to show up in the ng-repeat? Thanks!




Aucun commentaire:

Enregistrer un commentaire