$ cordovaContacts来自AngularJS Service

时间:2014-07-13 21:38:54

标签: angularjs ionic-framework

我正在尝试使用ngCordova module中定义的$ cordovaContacts服务。我试图在服务中获取手机联系人,以便我可以跨控制器使用它。

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
  });

问题是'$ scope.contacts'没有在控制器内设置。但是,当直接将服务代码放在控制器内而不使用服务时,代码可以正常工作。我一直试图找出问题所在。请帮忙!

1 个答案:

答案 0 :(得分:9)

    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;
    }

应该是

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

       //get the phone contacts
       return $cordovaContacts.find(options);
    }

和控制器

  $scope.contacts = ContactManager.getContacts().then(function(_result){
     $scope.contacts = _result;
  }, function(_error){
     console.log(_error);
  });