Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to read data from json and wait until data will be fetched into $scope.urls.content. So I write code:

$scope.urls = { content:null};
$http.get('mock/plane_urls.json').success(function(thisData) {
    $scope.urls.content = thisData;    
});

And now I am trying to write something like callback but that doesn't work. How can i do that? Or is there any function for this? I am running out of ideas ;/

share|improve this question
1  
What you wrote already contains a callback. Explain what you're trying to achieve please. –  finishingmove Jul 19 at 13:38
1  
What you see in networking tab of dev tools, do you ever have response from server ? is it with code 20x ? You are only defining success call back, which means it won't be fired in case of failure. –  vittore Jul 19 at 13:39
 
I am trying to use data what was fetched into $scope.urls.content but every time when i try use it immediately they have null. –  Mariola Jul 19 at 13:51

2 Answers

Do you mean that ?

$http.get('mock/plane_urls.json').success(function(thisData) {
    $scope.urls.content = thisData;
    $scope.yourCallback();
});
$scope.yourCallback = function() {
   // your code
};
share|improve this answer
 
I'm sure that yourCallBack would take a parameter of the returned data :). –  tymeJV Jul 19 at 15:34
1  
I believe it should be better to use promise API instead of calling a callback directly. It was designed for these needing.. –  CaioToOn Jul 19 at 15:38

You want to work with promises and $resource.

As $http itself returns a promise, all you got to do is to chain to its return. Simple as that:

var promise = $http.get('mock/plane_urls.json').then(function(thisData) {
  $scope.urls.content = thisData;
  return 'something';
});

// somewhere else in the code
promise.then(function(data) {
  // receives the data returned from the http handler
  console.log(data === "something");
});

I made a pretty simple fiddle here.

But if you need to constantly call this info, you should expose it through a service, so anyone can grab its result and process it. i.e.:

service('dataService', function($http) {
  var requestPromise = $http.get('mock/plane_urls.json').then(function(d) {
    return d.data;
  });

  this.getPlanesURL = function() {
    return requestPromise;
  };
});

// and anywhere in code where you need this info
dataService.getPlanesURL().then(function(planes) {
  // do somehting with planes URL
  $scope.urls.content = planes;
});

Just an important note. This service I mocked will cache and always return the same data. If what you need is to call this JSON many times, then you should go with $resource.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.