2014-04-30 80 views
1

我想从我的回调函数中获取联系人值。如何从回调函数中获取变量的值?

如何让我的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); 

    }; 
}; 
+0

您使用的是什么JavaScript库? –

+0

我不会工作,因为'这'是另一个背景。你可以将'this'存储在一个变量中并在回调中使用。 – Luketep

+0

它看起来像'.find'我是一个异步功能。在这种情况下,请看[如何从AJAX调用返回响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call )。 –

回答

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

非常感谢! – RonyRun

相关问题