I cant pass data from Service to Controller

Hello to all. I have a problem to pass data from service to controller. If you help me I’ll much appreciate. Here is my code:

This is my Books factory in service.js

.factory('Books',function($http){
        var books = [];

return {
          all: function() {
             $http({
                method: 'GET',
                    url: 'http://localhost/webservice/server/?a=kitaplarim',
                  }).success(function(data){
                    books=data;
                    //on console i can see my books data
                    console.log(books)
                    return books;
                  }).error(function(data){
                    alert("Faill!!!");
                  });
          }
        }
});

controller.js

.controller('KitaplarimCtrl', function($scope, Books) {
  $scope.books = Books.all();
  //in here I cant see anything on $scope.books
  console.log($scope.books) 
})

Because of $scope.books didn’t assigned in my template file I can’t see the data
template

<ion-item class="list card" ng-repeat="book in books" type="item-text-wrap" href="#/tab/kitaplarim/?a=detail&id={{book.id}}">
      <div class="item item-body">
        <img ng-src="{{book.img}}">
        <div class="bookInfoIndividual">{{book.name}}</div>
        <div class="bookInfoIndividual">{{book.publisher}}</div>
        <div class="bookInfoIndividual">{{book.author}}</div>
      </div>
 </ion-item> or paste code here

Are you sure you are not getting any console errors due to comma at the end of url field

No I made a typing mistake when I wrote it here :slight_smile:

Then i guess it is due to the $http promises
You will notice your controller getting called first and then your service

You have to return a promise, which will wait to finish before coming to controller. There are various ways to do this. One can be like

.factory('Books', function($http, $q){
   var all  = function(){
    var d = $q.defer();
    var books = [];
    $http.get('http://localhost/webservice/server/?a=kitaplarim').success(function(data){
       d.resolve(data);
});
return d.promise;
}
});

In Controller:

.controller('KitaplarimCtrl', function($scope, Books) {
     Books.all().then(function(books){
            $scope.Books = books;
         }
...
})
1 Like

Thank you so much for your solution it’s work correctly. In this way I learned I have a misunderstanding about conceptual of promise usage. For the other guys I belive this articles for more helpful what is happening in this code.
http://mcgivery.com/promise-based-architecture-in-an-ionic-app/
https://www.quora.com/What-is-q-defer-in-Angular-js-What-is-the-use-of-this