我使用 html5 地理定位 API 创建了此代码片段。
如果用户允许并使用 {{lat}}
我不明白为什么纬度仅在第二次单击时显示。 我以为 showPosition() 已经触发了? 您可以在第一次点击时看到它显示在控制台中。
HTML:
<body ng-controller="MainCtrl">
{{lat}}
<button ng-click="getLocation()">Click</button>
</body>
JS:
app.controller('MainCtrl', function($scope) {
$scope.getLocation = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
$scope.lat = "Latitude: " + position.coords.latitude;
$scope.lng = "Longitude: " + position.coords.longitude;
console.log($scope.lat);
}
});
最佳答案
回调函数showPosition
被称为“外部”Angular,因此虽然你的$scope
属性会被更新,但 View 不会更新,因为Angular不知道这些变化。
在函数 showPosition()
的底部调用 $scope.$apply()
。这将导致 digest cycle运行,Angular 将注意到您对 $scope 所做的更改(因为 Angular 由于在 HTML 中使用 {{}} 而设置了 $watches)并更新 View 。
关于javascript - 理解 $scope 和 angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15955984/