$cordovaContacts from within AngularJS Service


#1

I am trying to use $cordovaContacts service defined in the ngCordova module. I am trying to get the phone contacts in a service so I can use it across controllers.

Service.js

angular.module("services", ['ngCordova'])
  .factory("ContactManager", function($cordovaContacts) {
    var contacts; //variable that holds contacts, returned from getContacts

     return {
        getContacts: function() {
          var options = {};
           options.filter = "";
           options.multiple = true;

           //get the phone contacts
           $cordovaContacts.find(options).then(function(result) {
             contacts = result;
             }, function(err) {
           });
         return contacts;
        }
     }
  }) ;

Controller.js

angular.module("controllers", ['services'])
  .controller("ContactCtrl", function(ContactManager) {
     $scope.contacts = ContactManager.getContacts(); //this doesn't get set
  });

The problem is that ‘$scope.contacts’ does not get set inside the controller. However, when put the service code inside the controller directly without using the service, the code works. I have been trying to figure out what the problem is. Please help!


#2

Because your getcontacts method is not returning any thing. Way to do it is pass scope.contacts in method and set it to service contacts after it fetches results.


#3

assuming this is same question as stackoverflow

Here for reference: