0

I am trying to call a function but it returns undefines. However, the log shows the proper expected data.

app.controller('checkoutCtrl', function($scope, $http, $rootScope){

    $scope.finalizeOrder = function(){
        if($scope.ordersubmitform.$valid){
           //check if postal is valid
            alert($scope.thepostal($scope.customer.postal));
        } 
    }


    $scope.thepostal = function(postal){
        $http({
            method: 'GET',
            url: baseurl + 'api/verify_postal/' + postal,
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).then(function successCallback(response) {
                console.log(response.data.postal);
                return(response.data.postal);
            }, function errorCallback(response) {

            });
    }
});

The alert simply pops "undefined". However the console.log logs the expected answer.

Any idea?

I am not sure if using a service/factory is proper coz upon first calling the service/factory, I would get only its reference with out the function actually being called even if I try a different postal code. Sorry if I have gotten the whole singleton idea wrong.

Ela Buwa
  • 1,652
  • 3
  • 22
  • 43
  • Looks like an async call you are making in `thepostal` . The `alert()` executes immediately but the success callback is not executed until a later point in time. - Any code you want to execute using `response.data.postal` should be executed within/from the success callback. - Hence why your `console.log()` result is as expected. – Nope Jan 23 '17 at 09:44
  • yeah. Anyway to work around it? – Ela Buwa Jan 23 '17 at 09:50
  • Yes...as I said, any code you want to execute using the response data you have to write inside your successcallback where your `console.log()` is in and remove the `return`, if you want to use the response in other methods, call them from the successcallback passing the response as a parameter. – Nope Jan 23 '17 at 09:52
  • Yeah. I thought of making the stuff look more clearer by putting the call in to function. thanks again. – Ela Buwa Jan 23 '17 at 09:57
  • Hi, I think change this syntax will work. `return response.data.postal;' can you try.. – Yuvraj Singh Jan 23 '17 at 10:01

0 Answers0