0

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.

1
  • this isn't what you think it is, and therefore doesn't have a movie property. Commented Mar 5, 2015 at 22:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.