shanwar shanwar - 2 months ago 7
Javascript Question

Service returning undefined to the controller

This is my service:

'use strict';

app
.service('myService', function($http) {

this.getJSON = function() {
return $http.get('someUrl/dataForm').then(function(data){
return data.result;
});
};
});


And in my controller I have:

'use strict'
app.controller('myController', function ($scope, myService) {

myService.getJSON().then(function(data){
$scope.myData =data;
});
console.log($scope.myData);
});


I can see that the http call is successfully returning a JSON value but the console log shows that the value of myData is undefined.
What am I doing wrong ?

Answer

Place the console.log inside

 myService.getJSON().then(function(data){
                $scope.myData =data;
                console.log($scope.myData);
 });

DEMO