Search code examples
angularjsangularjs-scopeangularjs-serviceangular-promise

Return resolved $resource within service


I'm new to writing services. I'm calling a method on my factory which calls a series of operations.

1) Get data from DB 2) Wait for the $promise to resolve and then compare & filter the results 3) return new filtered list

All I get when I log out $scope.new_list is an empty object. Can someone help me with what I'm doing wrong?

  people.factory('uniqueContacts', ['apiResource', function(apiResource) {
    function getDB() {
         return apiResource.query({api_resource:'people'})
  }
  function generateList(newlistdata){
    getDB().$promise.then(function(result){

           newlist = _.difference(newlistdata, result);
         })
          return new_list;
    });
  }
    return{
      buildList: function(newlistdata){
        return generateList(newlistdata);
      }
    }
  }]);


//in my controller
  $scope.new_list = uniqueContacts.buildList(newlistdata);
  console.log($scope.new_list) // undefined

Solution

  • Your service function should return new_list from success

    getDB().$promise.then(function(result){
           newlist = _.difference(newlistdata, result);
           return new_list;
         })
    });
    

    Controller

     uniqueContacts.buildList(newlistdata).then(function(new_list){
       $scope.new_list = new_list;
     });