0

I want to move this function to services.js:

News.all().async().then(function(data) {
  $scope.news = data['data']['NewsList'];
});

And than call it in controller.js by this command:

$scope.news = News.all();

I try many ways, but them did not work.

Here is my services.js:

.factory('News', function($http) {
  function returnNews() {
    return {
      async: function() {
        return $http.get('test.json');
      }
    };
  }
  return {
    all: function() {
      return returnNews();
    }
  }
});

1 Answer 1

1

Well if you call News.all() in the end you will get an object with an async property: {async} and I don't think this is what you want. What you can do is pass a callback to the service:

.factory('News', function($http) {
  return {
    all: function(callback) {
      return $http.get('test.json').then(callback);
    }
  }
});

and in the controller you have to do:

News.all(function(data){
  $scope.news = data
});
Sign up to request clarification or add additional context in comments.

2 Comments

This seems like an anti-pattern. Instead of converting a promise into a traditional callback-style async operation, just expose the promise and chain to it. News.all().then(function (data) ... and have News.all return $http.get('test.json')
Yes, or you can do as @WilliamB sugested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.