如何从$.get jquery更新angularjs $scope?
如何从$.get jquery更新angularjs $scope?
我正在尝试使用以下代码并使用$scope
:\n
var scopes = "https://www.googleapis.com/auth/contacts.readonly"; setTimeout(authorize(), 20); function authorize() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization); } invitePeersController.gmailContacts = []; function handleAuthorization(authorizationResult) { if (authorizationResult && !authorizationResult.error) { $.get("https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=" + authorizationResult.access_token + "&max-results=50000&v=3.0", function(response){ //在这里处理响应 console.log(response); var jsonChildData = JSON.parse(JSON.stringify( response.feed.entry)); for(var i=0; i\n我可以在
$scope
中获取响应,但无法在其他地方获取数据。\n如何在$scope
中使用那个值?\n尝试遵循这个问题,并应用$scope.$apply()
,但它不起作用。
问题出现的原因是在$.get()的回调函数中更新了invitePeersController.gmailContacts的值,但是$scope的更新操作却没有生效。解决方法是将更新$scope的操作放到$apply函数中。
以下是整理后的文章:
您需要将以下代码块移动到function(response){}
中,以便在响应返回时初始化invitePeersController.gmailContacts
- 因为响应是在回调函数中进行的。
因此:
var scopes = "https://www.googleapis.com/auth/contacts.readonly"; setTimeout(authorize(), 20); function authorize() { gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthorization); } invitePeersController.gmailContacts = []; function handleAuthorization(authorizationResult) { if (authorizationResult && !authorizationResult.error) { $.get('https://www.google.com/m8/feeds/contacts/default/thin?alt=json&access_token=' + authorizationResult.access_token + '&max-results=50000&v=3.0', function (response) { //在这里处理响应 console.log(response); var jsonChildData = JSON.parse(JSON.stringify(response.feed.entry)); for (var i = 0; i < jsonChildData.length; i++) { try { var item = {}; var name = JSON.stringify(jsonChildData[i].title.$t); var email = JSON.stringify(jsonChildData[i].gd$email[0].address); if (name.substring(1, name.length - 1) && email.substring(1, email.length - 1)) { item ['name'] = name.substring(1, name.length - 1); item ['email'] = email.substring(1, email.length - 1); item ['id'] = email.substring(1, email.length - 1).replace(/[^a-zA-Z ]/g, ''); invitePeersController.gmailContacts.push(item); } InvitePeersService.setGmailContactsData(invitePeersController.gmailContacts); console.log(invitePeersController.gmailContacts); $scope.$apply(function () { $scope.gmailData = invitePeersController.gmailContacts; console.log($scope.gmailData); }) } catch (err) { // console.log("Something went terribly wrong while trying to fetch Gmail Contacts Data"); } } }); } }
仍然是相同的问题。