0

このスニペットは、html5 geolocation api を使用して作成しました。ユーザーが緯度経度を許可して表示する場合{{lat}}

緯度が 2 回目のクリックでのみ表示される理由がわかりません。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);
  }
});
4

1 に答える 1

2

コールバック関数showPositionは Angular の「外部」と呼ばれるため、$scopeプロパティは更新されますが、Angular はこれらの変更を認識しないため、ビューは更新されません。

$scope.$apply()function の一番下で呼び出しますshowPosition()。これによりダイジェスト サイクルが実行され、Angular は $scope に加えられた変更を認識し (HTML で {{}} を使用するために Angular が設定した $watches のため)、ビューを更新します。

于 2013-04-12T03:47:11.523 に答える