如何从回调函数中获取变量的值?

时间:2014-04-30 10:32:18

标签: javascript angularjs cordova

我想从我的回调函数中获取联系人值。

如何拥有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);

  };
};

1 个答案:

答案 0 :(得分:0)

问题在于,当您处于回调中时,您对this的引用不是您的封闭对象。您需要使用angular.bind传递对象的上下文。

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);
相关问题