繁体   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