sergei
sergei

Reputation: 157

angular/javascript not recognizing global variable inside function

I did a service that gets me a movie info from omdb api but when I'm trying to use it from my controller and push the result to my movie array it complains about

TypeError: Cannot read property 'push' of undefined

.controller('AppCtrl', function(omdbApi) {
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            this.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

Can someone explain why is it unable to push to movie? I'm not sure it's an angular problem but from javascript point I really don't get it. I've tested that the incoming data is legit. If I just assign the data to movie then I'm unable to access it outside the function.

Upvotes: 0

Views: 270

Answers (1)

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

This is a common mistake. this object in your .then() callback does not refer to the same object of .controller() callback. Use a closure:

.controller('AppCtrl', function(omdbApi) {
    var self = this; // <---- this is the key
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            self.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

Another option is to use Function.prototype.bind() to force a context.

Upvotes: 1

Related Questions