简体   繁体   中英

Why doesn't AngularJS service bind to scope?

Angular noob trying to follow this geolocation example for watchPosition verbatim using Angular 1.2.21. Browser debuggers show the service position object is updated when GPS fires however scope myCoords remains undefined. I've tried adding $apply in a couple places which throws apply is in progress. What's wrong here and which concepts do I need to read up on ?

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
    }]);

The coords property of $geolocation.position gets re-assigned with every update. It's the position object of $geolocation` that stays the same.

So, (based on how you want to use it) you should write something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM