为什么AngularJS的服务不绑定到作用域?

Why doesn't AngularJS service bind to scope?

本文关键字:作用域 绑定 AngularJS 服务 为什么      更新时间:2023-09-26

Angular新手试图使用Angular 1.2.21逐字逐句地学习这个地理定位示例。浏览器调试器显示,当GPS触发时,服务位置对象被更新,但范围myords仍然未定义。我试过在几个地方添加$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属性在每次更新时被重新分配。这是position object of $geolocation '保持不变。

所以,(基于你想如何使用它)你应该这样写:

$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);