Bipin Butala
Bipin Butala

Reputation: 175

Calling Ajax service using callback function

I am trying to call a web service using ajax and then pass the results to an angular controller. I cannot get the values out of the callback function to pass into a scope variable. I think it's just my bad understanding of how the callback function works.

here is the code:

function ajaxKimono(callback) {

    $.ajax({
          url:"https://www.kimonolabs.com/api/cveeggn4?apikey=NWYzkeJpFDtb4aOYd6yD96L5PdLuZHjo",
          crossDomain: true,
          dataType: "jsonp",
          success: callback,
          error: function (xhr, status) {
            //handle errors
            console.log(xhr);
            console.log(status);
          }
        });

};

angular.module('app').controller('gifCtrl', function(){
    var self = this;
    var gifs = [];

    ajaxKimono(function(result){
        var collection = result.results.collection1;

        $.each(collection, function(i, item){
            gifs.push({ gif: item.property5.href});
        });

        //this outputs the correct data
        //so i know the ajax call is working correctly
        console.log(gifs);

        self.gifCollection = gifs;

    });

    //something about the scope is messing me up
    //this outputs nothing...
    console.log(self.gifCollection);

});

Upvotes: 2

Views: 1371

Answers (1)

sjokkogutten
sjokkogutten

Reputation: 2095

As mentioned in the comments, I guess the problem is that your console.log is called before your request has finished.

Place your http request in a separate factory or service. This makes testing and re-use easier. Note the use of angular's $http shortcut methods which returns a promise:

app.factory('DataService', function($http) {
  var getValues= function() {
    return $http.jsonp("/api/...") // returns a promise
  };

  return {
    getValues: getValues
  }
});

And then in your controller:

myApp.controller('MyController', function ($scope, DataService) {     
    DataService.getValues().then(
    function(){
      // successcallback
    },
    function(){
      // errorcallback
    })   
});

Note that I have not implemented the above code, but should provide you with an outline

Upvotes: 2

Related Questions