简体   繁体   中英

How to get the value of a variable from a callback function?

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

  };
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM