J
J
jack3d2015-08-07 16:38:15
JavaScript
jack3d, 2015-08-07 16:38:15

Why in angular outside of query data is undefined?

factory:

angular.module('sample').factory('PostService', ['$resource', '$rootScope', '$q',
  function ($resource, $rootScope, $q) {
    var PostService = $resource('/api/:action/:hub_id/posts', {}, {
      posts: {
        method: 'GET',
        params: { action: 'feed', hub_id: '90f9a03', isArray: false }
      };

    return PostService;
  }]);

In controller:
$scope.getPosts = PostService.posts(function(posts) {
      $scope.posts = posts.results;
        console.log($scope.posts); //work
    });
      console.log($scope.posts); //undefined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Kononenko, 2015-08-07
@premas

Because JavaScript is executed asynchronously. You can't freeze everything and wait for a response from the server. Either work in callback closures or master promises.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question