簡體   English   中英

AngularJS服務為什么不綁定到作用域?

[英]Why doesn't AngularJS service bind to scope?

Angular noob嘗試使用Angular 1.2.21逐字跟蹤watchPosition的此地理位置示例。 瀏覽器調試器顯示,當GPS觸發時,服務位置對象已更新,但是范圍myCoords仍未定義。 我試過在幾個地方添加$ apply,正在拋出異常。 這里有什么問題,我需要閱讀哪些概念?

angular
    .module('myApp', ['ngGeolocation'])
    .controller('geolocCtrl', ['$geolocation', '$scope', function($geolocation, $scope) {
        $geolocation.watchPosition({
            timeout: 60000,
            maximumAge: 250,
            enableHighAccuracy: true
        });
        $scope.myCoords = $geolocation.position.coords; // not updated
        $scope.myError = $geolocation.position.error; // this becomes truthy, and has 'code' and 'message' if an error occurs
    }]);

$geolocation.positioncoords屬性在每次更新時都會重新分配。 $ geolocation`的position object of保持不變。

因此,(根據您的使用方式)您應該編寫如下內容:

$scope.myPosition = $geolocation.position;

<!-- If you want to use it in the VIEW -->
<p>Latitude:   {{myPosition.coords.latitude}}</p>
<p>Longtitude: {{myPosition.coords.longtitute}}</p>
<p ng-show="myPosition.error">
    Error ({{myPosition.error.code}}): {{myPosition.error.message}}
</p>

/* Or if you want to manually $watch for changes in coords */
$scope.$watch('myPosition.coords', function (newValue, oldValue) {...}, true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM