Search code examples
angularjsionic-frameworkngcordova

Get and manipulate phone contacts by ngCordova in Ionic app


I want to get all phone contacts by $cordovaContacts and manipulate them to send for server. like this

$scope.contacts = [];

$cordovaContacts.find({
      filter: '', 
      fields: ['displayName','phoneNumbers']
}).then(function (allContacts) {

    angular.forEach(allContacts, function (contact, index) {
          $scope.contacts.push({
              "first_name": contact.name.givenName,
              "last_name": contact.name.familyName,
              "phone_number": contact.phoneNumbers[0].value
          });
    });
});

HTML

<p style="white-space: pre;">{{contacts | json: 3}}</p>

But angular.forEach not working and there is No error, whats wrong?


Solution

  • Finally solve the problem ::

    $cordovaContacts.find({
          filter: '', 
          fields: ['displayName', 'name', 'phoneNumbers']
    }).then(function (allContacts) {
    
        var contacts = [];
    
        angular.forEach(allContacts, function (contact, index) {
    
           if (contact.phoneNumbers != null && 
               contact.phoneNumbers[0].type == 'mobile' &&
               contact.name != null) {
    
               // if user have firstName and lastName
               if (contact.name.givenName && contact.name.familyName) {
    
                 contacts.push({
                    "first_name": contact.name.givenName,
                    "last_name": contact.name.familyName,
                    "phone_number": contact.phoneNumbers[0].value
                 });
    
               } else {
    
                 contacts.push({
                    "first_name": contact.name.givenName ? contact.name.givenName : '',
                    "last_name": contact.name.familyName ? contact.name.familyName : '',
                    "phone_number": contact.phoneNumbers[0].value
                 });
    
               }
    
            }
    
        });    
    
    });