Sirwan Afifi
Sirwan Afifi

Reputation: 10824

AngularJS: How to get $http result as returned value of a function?

Inside my controller I need a function that takes a parameter and returned a URL from server. Something like this:

$scope.getPoster = function(title) {
    return $http.get("http://www.omdbapi.com/?t=" + title + "&y=&plot=short&r=json");
};

And inside my view I need to pass the title this way and get result as src for ng-src:

<div class="col-sm-6 col-md-3" ng-repeat="movie in movies">
    <div class="thumbnail">
        <img class="poster" ng-src="{{getPoster(movie.Title)}}" alt="{{movie.Title}}">
        <div class="caption">
            <h3>{{movie.Title}}</h3>
            <p>{{movie.Owner}}</p>
        </div>
    </div>
</div>  

I know the HTTP communications on $http never ever return data that I need immediately because all communications are asynchronous So I need to use promise:

$scope.getPoster = function(title) {
    $http({ url: "http://www.omdbapi.com/?t=" + title + "&y=&plot=short&r=json" }).
    then(function (response) {
        // How can I return response.data.Poster ? 
    });
};

So my question is that How can I return the response as result for getPoster function?
Any idea?

Upvotes: 2

Views: 3542

Answers (4)

byrdr
byrdr

Reputation: 5467

Here's another approach, this may work better for you.

Template:

<div class="col-sm-6 col-md-3" ng-repeat="movie in getMovies">
<div class="thumbnail">
    <img class="poster" ng-src="{{movie.Poster}}" alt="{{movie.Title}}">
    <div class="caption">
        <h3>{{movie.Title}}</h3>
        <p>{{movie.Owner}}</p>
    </div>
</div>

Service:

function getMovieData(movies) {
return {
    loadDataFromUrls: (function () {
        var apiList = movies;

        return $q.all(apiList.map(function (item) {
            return $http({
                method: 'GET',
                url: "http://www.omdbapi.com/?t=" + item + "&y=&plot=short&r=json"
            });
        }))
        .then(function (results) {
            var resultObj = {};
            results.forEach(function (val, i) {
                resultObj[i] = val.data;
            });
            return resultObj;        
        });
    })(movies)
};
};

Controller:

var movies = ["gladiator", "seven"];  

$scope.getMovies = getMovieData(movies);

function getMovieData(){
dataService.getMovieData(movies).loadDataFromUrls
  .then(getMovieDataSuccess)
  .catch(errorCallback);
}


function getMovieDataSuccess(data) {
    console.log(data);
    $scope.getMovies = data;
    return data;
  } 

Upvotes: 0

falsarella
falsarella

Reputation: 12437

If you pass movie to getPoster function, instead of title, it should work; and bind a variable to ng-src instead of the return of the getPoster function, it should work.

Also, you could display a placeholder while you are waiting for the response:

HTML:

<img class="poster"
     ng-init="movie.imgUrl = getPoster(movie)"
     ng-src="{{movie.imgUrl}}"
     alt="{{movie.Title}}">

* Note that ng-init could certainly be replaced with an in-controller initialization.

JS:

$scope.getPoster = function(movie) {
    $http({ url: "http://www.omdbapi.com/?t=" + movie.Title+ "&y=&plot=short&r=json" })
    .then(function (response) {
        movie.imgUrl = response.data.Poster;
    });
    return "/img/poster-placeholder.png";
};

Once the response is returned, movie.imgUrl is changed.

So, the image will automatically be updated with the new source in the next digest cycle.

With this example, you won't need to return the promise.

Upvotes: 2

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6883

Here is the working jsFiddle of your case. Note, i have taken sample titles.

You can't call the function in ng-repeat. You need to get the values before its been loaded like using resolve.

     var app = angular.module('myApp',[]);
app.controller('myCtrl',function($http,$scope){

          $scope.movies =[{Title:'gene',Owner:'Alaksandar'},{Title:'alpha',Owner:'Me'}];
            angular.forEach($scope.movies,function(movie){
                $http.get("http://www.omdbapi.com/?t="+movie.Title+"&y=&plot=short&r=json").
                        success(function (response) {
                            movie['poster'] = response.Poster;
                    });


            });
});

Upvotes: 1

rakesh
rakesh

Reputation: 129

As you are using ng-repeat, you can pass the whole movie object, and then can add a new property to it:

$scope.getPoster = function (movie) {
    $http({ url: "http://www.omdbapi.com/?t=" + movie.Title + "&y=&plot=short&r=json" }).
            then(function (response) {
                // How can I return response.data.Poster ? 
                movie.imageUrl = response.data.Poster;
            });
};

and then bind ngSrc:

ng-src='{{movie.imageUrl}}'

Upvotes: 2

Related Questions