Start a new topic

Angular Factory/Controller Syntax

Hi, I'm not sure what I am doing wrong and I've been searching for a while and would be grateful for some help. 

I have the following in a controller to retrieve a collection:


And this works fine 

.controller('EmployeeListController',['$scope', '$kinvey', function($scope, $kinvey){
    $scope.employees = [];
    var promise = $kinvey.DataStore.find('Employees');
    promise.then(function(employees){
        $scope.employees = employees
        })
}])

 However I need to create a factory instead so that this data can be shared with another controller so I did this: 

  

.factory('employeeList',['$kinvey', function($kinvey){
   return { employee: function(){
                    var promise = $kinvey.DataStore.find('Employees');
                    promise.then(function(response){
                    return response })
                    }
            }
}])

  and for the controller 

.controller('EmployeeListController',['$scope', 'employeeList', function($scope, employeeList){
    $scope.employees = employeeList.employee()
}])

 But it doesn't work. Help! Thanks...


Nashira,


Can you be a little more specific on what didn't work there?  Did nothing happen?  Did you see any errors?  If so what were they?


Thanks,

Actually this didn't work either... :-/

Hello Nashira,


Our engineer Thomas took a look at your code and produced this for you.   We believe that this should solve the issue and give you a better understanding of how the factory works in general.


Please let us know if you have any additional questions,


  

.factory('EmployeeCollection', ['$q', '$kinvey', function($q, $kinvey) {
   var employees = [];
   var deferred;
   
   var EmployeeCollection = { 
      $fetch: function(options) {
         // Set default options
         options = options || {};
         
         // Only fetch from Kinvey if we a deferred does not already exist
         // or options.force is true
         if (!deferred || options.force) {
            // Create a deferred
            deferred = $q.defer();
            
            // Fetch the employees from Kinvey
            $kinvey.DataStore.find('Employees').then(function(response) {
               // Store the employees
               employees = response;
               
               // Resolve the promise with the employees
               deferred.resolve(employees);
            }, function(error) {
               // Reject the promise with the error
               deferred.reject(error);
            });  
         }
         
         // Return the promise
         return deferred.promise;
      }
   };
   
   return EmployeeCollection;
}])

.controller('EmployeeListController', ['$scope', 'EmployeeCollection', function($scope, EmployeeCollection) {
    $scope.employees = [];
    
    EmployeeCollection.$fetch().then(function(employees) {
       $scope.employees = employees;
    });
}])

  

Login or Signup to post a comment