代码之家  ›  专栏  ›  技术社区  ›  ajayel

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

  •  0
  • ajayel  · 技术社区  · 11 年前

    试图跟随的角落 this geolocation 使用Angular 1.2.21逐字查看位置的示例。浏览器调试器显示,当GPS触发时,服务位置对象会更新,但范围myCoords仍然未定义。我尝试过在几个地方添加$apply,而throws 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
        }]);
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   gkalpak    11 年前

    这个 coords 的属性 $geolocation.position 每次更新都会被重新分配。这是 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);