0

I have a controller that calls a data service that I am sure returns data because when I log it inside the function that calls the data service I see returned data but when I use the variable in my scope it is empty

Code

console.log("This is the Plans view controller");
var vm = this;
vm.schemes = [];
getScheme();
console.log(vm.schemes);
getCategoryBenefits();
vm.createPlan = createPlan;

function getScheme() {

    return insurer.getSchemes()
        .then(function(response) {
            //console.log(response);
            vm.schemes = response;
            return vm.schemes;
        });
};

console.log(vm.schemes); //This is logged in console as []

and here is the service code

        function getSchemes(){
            return $http.get(urlBase + 'plans/schemes/')
                .then(getSchemeComplete)
                .catch(getSchemeFailed);

                function getSchemeComplete (response) {
                    return response.data;
                }

                function getSchemeFailed (error) {
                    return error;
                }
        }

Please help maybe I missed something.

In this case the problem is that the data can only be accessed inside the function that calls the data services and cannot be assigned to a varible that is global lest it return an undefined/empty value

dadidaochieng
  • 105
  • 13
  • Please post the html that interacts with this controller. – Benjamin Schüller Jun 27 '16 at 08:20
  • 1
    I've linked this to the generic "How do I [do] asynchronous calls?" question. The top answer(s) there should get you going. (The short answer is that the value isn't set in the callback function until *after* you try to log it outside the function.) – nnnnnn Jun 27 '16 at 08:25
  • The problem is the variable vm.schemes that I assign to the data return is undefined when accessed outside the function. Please clarify – dadidaochieng Jun 27 '16 at 08:45

0 Answers0