我已经搞了 2 个小时了,找不到解决方案。 下面是显示日志的 chrome 开发工具输出。
(按顺序)
3 - 未定义
1 - 检查
2 - Google 用户
为什么我的 html 中的 place 变量没有更新为“A Google User”?
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', '$log',
function($scope, $http, $log) {
var request = {
placeId: 'ChIJX3piIfJ4j4ARXuQlqgn6LaA' //Walmart HQ
};
service = new google.maps.places.PlacesService(map);
service.getDetails(request, function(place, status) {
$log.log('1 - check');
$log.log('2 - ' + place.reviews[0].author_name);
$scope.place = place.reviews[0].author_name;
});
$log.log('3 - ' + $scope.place);
}
]);
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Place details</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js'></script>
<script src="app.js"></script>
</head>
<body>
<div id="map"></div>
<div ng-controller='AppCtrl'>
{{ place }}
</div>
</div>
</body>
</html>
最佳答案
google.maps.places.PlacesService
不是内置的异步处理程序,您需要在异步调用后运行 $scope.$apply
。使用 $scope.$apply
更新 View :
$scope.$apply(function () {
$scope.place = place.reviews[0].author_name;
});
更新 1
检查 $apply
:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.
当发生可能更新时,Angular 执行脏检查。 XHR 调用不在范围内。 Angular 不会更新 View ,除非您通过$apply
要求它进行脏检查。
最佳实践是:尽可能使用 Angular 内置提供程序,例如 $timeout
、$http
。或 ng-click
、ng-change
等。这些将隐式调用 $apply
。
关于javascript - Angular 代码未显示在 html 页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978203/