angularjsangularjs-ng-resource

Sending data from Angular 1.x Factory to Angular 1.x controller


I have a service defined which do the db related queries/updates. I have defined the controller which does the data parsing for the angular elements by getting the objects from the service. I would like to keep each scope different

How can I pass the data from service to controller using ngResource.

Sample Service:

app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
   var svc = {};
   var home = $resource('/home/getAll');
   var dbData= home.get();
   svc.getRooms = function() {
       return dbData;
   };
    return svc;
}]);

Sample Controller:

app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
    $scope.dbData = ioHome.getRooms();
    //Here UI specific objects/data is derived from dbData
}]);

After the DB is queried and the results are avialble the dbData in service is reflecting the data from DB, but the Controller cannot get that data


Solution

  • It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.

    From https://docs.angularjs.org/api/ngResource/service/$resource

    Since the 'ioHome.getRooms();' is being called before the $resource has returned the data you are getting dbData as an empty reference

    app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
       var svc = { 
         dbData : {}
       };
       var home = $resource('/home/getAll');
       var svc.dbData.rooms = home.get();
       return svc;
    }]);
    

    Controller

    app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
        $scope.dbData  = ioHome.dbData;
    
        //You can access the rooms data using $scope.dbData.roooms
    
        //Here UI specific objects/data is derived from dbData
    }]);