-1

Im currently messing around learning Angular. I have a controller thats hooked up to a radial progress bubble, i am creating a factory that uses $http to grab some dummy data from data.json I inject the factory into my controller and set that data into a variable so i can use it inside some other objects. To be exact, i want to take the first element of the returned array from my json file as the dashOffset property on the circle object. The current console.log inside my controller prints Undefined but the console.log in my factory prints out the correct array.

var app = angular.module('app',['ui.router']) .factory('Data', function($http){ return { getData : function(callback){ $http.get('data.json').success(function(res){ console.log(res) }); } } }) .controller('radial', function($scope, Data){ $scope.ryan = Data.getData(); console.log($scope.ryan); $scope.circle = { size : 110, stroke : '#2C3E50', strokeWidth : 10, radius : 48, dashArray : Math.PI * 2 * 48, dashOffset : (Math.PI * 2 * 48) } $scope.circleBG = { size : 110, stroke : '#2C3E50', strokeWidth : 10, radius : 48, dashArray : Math.PI * 2 * 48, dashOffset : (Math.PI * 2 * 48) } }); 
3
  • That is because you are really not returning anything from your factory method Commented Jan 27, 2015 at 1:44
  • possible duplicate of How to use HTTP.GET in AngularJS correctly? In specific, for an external API call? Commented Jan 27, 2015 at 1:46
  • Oh, i see, but even when i add return res to the end of the success function it still prints undefined Commented Jan 27, 2015 at 1:47

1 Answer 1

0

2 things 1->you are not really returning anything in your getData method 2-> getData is an asynchronous operation so by the time the function returns there is no data to view yet

there are 2 ways of achiving what you want

1->callbacks 2-> promises 

using callbacks you can do something like in your controller

assuming you return the $http.get you can do

//using success callback Data.getData() .success(function(data){ $scope.ryan=data; console.log($scope.ryan) }); //using promises Data.getData() .then(function(response){ return response.data }) .then(function(ryan){ $scope.ryan=ryan; console.log(ryan) }) 

for more on this review

https://docs.angularjs.org/api/ng/service/$http

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.