Joe Lloyd
Joe Lloyd

Reputation: 22373

Moving code from controller to a factory breaks the code, why?

I'm moving my code from the .controller to a factory

here is the code that works from the controller

.controller('ChatsCtrl', function ($scope, $http, $rootScope) {
  $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
    $scope.chats = response;
  });
})

I want this to be refactored to a factory so the controller looks like this

.controller('ChatsCtrl', function ($scope, Chats) {
  $scope.chats = Chats.all();
})

So the factory is like this

.factory('Chats', function() {
    return {
      all: function ($scope, $http, $rootScope) {
        return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } }).success(function (response) {
            $scope.chats = response;
        });
      }
    };
});

So when I move the code to the factory it doesn't pull anything from my database. I have referenced the 'Chats' factory in the controller but it doesn't seem to pull the data through.

Upvotes: 1

Views: 109

Answers (2)

whatoncewaslost
whatoncewaslost

Reputation: 2256

Return the promise to set and assign it to the scope in the controller. So more like this.

.controller('ChatsCtrl', function ($scope, Chats) {
  Chats.all().success(function (data) {
    $scope.chats = data;
  })
})

.factory('Chats', function($http, $rootScope) {
  return {
    all: function () {
      return $http.get('http://<my_ip>:<my_port>/chats', 
        { params: { user_id: $rootScope.session } })
    }
  };
});

Upvotes: 1

Ana F
Ana F

Reputation: 641

You can return a promise from the factory and do .success in the controller(optionally with a cache in the factory if your data doesn't change)

.factory('Chats', function() {
    return {
      all: function ($scope, $http, $rootScope) {
        return $http.get('http://<my_ip>:<my_port>/chats', { params: { user_id: $rootScope.session } })
      }
    };
});


.controller('ChatsCtrl', function ($scope, Chats) {
     Chats.all().success(function (response) {
         $scope.chats = response;
     });
})

Upvotes: 1

Related Questions