【问题标题】:Why doesn't AngularJS service bind to scope?为什么 AngularJS 服务不绑定到作用域?
【发布时间】:2014-08-09 03:03:50
【问题描述】:

Angular 菜鸟尝试使用 Angular 1.2.21 逐字跟随 this geolocation 示例进行 watchPosition。浏览器调试器显示服务位置对象在 GPS 触发时更新,但范围 myCoords 仍未定义。我已经尝试在抛出 apply 的几个地方添加 $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
    }]);

【问题讨论】:

  • 您是否尝试过将代码包装在 $timeout 中?
  • 但你确定你的 $geolocation.position.coords 包含你需要的数据吗?我的意思是你确定它返回的数据是什么并且它不是未定义的

标签: javascript angularjs binding geolocation


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-31
    • 2011-12-04
    • 2014-12-17
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多