1

I want to get the contacts value from my a callback function.

How to have my this.recherche = contacts ?

App.provider('ContactsP', function() {

this.$get = function() {
  return function(search) {

    console.log('Factory ContactsCtrl RECHERCHE : ' + search);

    this.recherche = [];
    this.options = new ContactFindOptions();
    this.options.filter = search;
    this.options.multiple = true;
    this.fields = ["displayName", "name", "phoneNumbers"];

    navigator.contacts.find(this.fields, function(contacts) {

      //I want to put contacts into this.recherche but that doesn't work....

     this.recherche = contacts; return contacts;

    }, function(e) {
      console.log("Error finding contacts " + e.code)
    }, this.options);

  };
};
RonyRun
  • 35
  • 6
  • What javascript library are you using? – Abimbola Esuruoso Apr 30 '14 at 10:35
  • I wont work because 'this' is another context then. You could store 'this' in a variable and used that inside the callback. – Luketep Apr 30 '14 at 10:36
  • It looks like `.find` my be an asynchronous function. In that case, have a look at [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). – Felix Kling Apr 30 '14 at 10:43
  • Hi, thank you. It's on angularJS and Cordova. Felix : I try and tell you. – RonyRun Apr 30 '14 at 11:12

1 Answers1

0

The problem is that when you are in the callback your reference to this is not your enclosing object. You need to use angular.bind to pass in the context of your object.

navigator.contacts.find(this.fields, angular.bind(this, function(contacts) {

      //I want to put contacts into this.recherche but that doesn't work....

     this.recherche = contacts; return contacts;

    }), function(e) {
      console.log("Error finding contacts " + e.code)
    }, this.options);
codemonkey
  • 5,257
  • 2
  • 18
  • 16