如何使angularJS控制器始终处于活动状态?

时间:2016-08-20 15:10:00

标签: angularjs cordova

我正在开发一个angularJS应用程序,我的设备中的地理坐标每隔几秒就被带到我的REST服务中。地理坐标发送代码仅位于一个控制器中。这意味着只有在该控制器的模板页面打开时,才会在我的服务器中更新地理位置。我如何做到这一点,无论我在哪个页面,地理定位总是更新。

以下是该控制器的代码:

.controller('geolocationCtrl', [ '$scope', '$http', 'geolocationFactory',
        function($scope, $http, geolocationFactory) {

            // constants should be uppercase
            var GET_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation',
                PUT_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation/update';


            $http.get(GET_PATH).then(function (response) {
                var respLong = Number(response.data.longitude),
                    respLat = Number(response.data.latitude);

                $scope.map = drawMap(respLong, respLat);
                $scope.marker = new google.maps.Marker({
                    position: new google.maps.LatLng(respLong, respLat)
                });
                $scope.marker.setMap($scope.map);

            }, function (errorResponse) {
                console.error('error response ' + errorResponse);
            });

            function drawMap(latitude, longitude) {
                var lat = latitude,
                    long = longitude,
                    currentLatlng = new google.maps.LatLng(lat, long);
                var map = new google.maps.Map(document.getElementById('map'), {
                    center: currentLatlng,
                    zoom: 10
                });
                return map;
            };

            setInterval(function () {
                geolocationFactory.getCurrentPosition().then(function(location) {

                    var newLatitude = location.coords.latitude,
                        newLongitude = location.coords.longitude;

                    // delete old marker
                    $scope.marker.setMap(null);
                    $scope.marker = new google.maps.Marker({
                        position: {
                            lat: newLatitude,
                            lng: newLongitude
                        }
                    });
                    var LatLng = new google.maps.LatLng(newLatitude, newLongitude);
                    $scope.map.setCenter(LatLng);
                    $scope.marker.setMap($scope.map);


                    // send data to server
                    $http.put(PUT_PATH, {
                        "longitude": newLatitude,
                        "latitude": newLongitude
                    }).then(function (response) {
                        console.log('data sended');
                    }, function (errorResponse) {
                        console.error(errorResponse);
                    });
                }.bind(this));

            }, 2000);

        }])

这是我的service.js

angular.module('app.services', [])

.factory('BlankFactory', [function(){

}])

.service('BlankService', [function(){

}])
.factory('geolocationFactory', ['$window', '$rootScope', '$q', function ($window, $rootScope, $q) {

    function supported() {
        return 'geolocation' in $window.navigator;
    }

    var retVal = {
        getCurrentPosition: function (options) {
            var deferred = $q.defer();
            if (supported()) {
                $window.navigator.geolocation.getCurrentPosition(
                    function (position) {
                        $rootScope.$apply(function () {
                            this.coords = position.coords;
                            this.timestamp = position.timestamp;
                            deferred.resolve(position);
                        });
                    },
                    function (error) {
                        $rootScope.$apply(function () {
                            deferred.reject({error: error});
                        });
                    }, options);
            } else {
                deferred.reject({
                    error: {
                        code: 2,
                        message: 'This web browser does not support HTML5 Geolocation'
                    }
                });
            }
            return deferred.promise;
        },

        drawMarker: function (lat, lng) {

            map = new google.maps.Map(document.getElementById("map"), mapOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "Hello World!"
            });
        }
    };
    return retVal;
}]);

1 个答案:

答案 0 :(得分:0)

将间隔查询移动到服务中。当发生更改时,触发控制器侦听的事件以更新其范围。

修改后的服务:

angular.module('app.services', [])

.factory('BlankFactory', [function(){

}])

.service('BlankService', [function(){

}])
.factory('geolocationFactory', ['$window', '$rootScope', '$q', '$interval', '$http', function ($window, $rootScope, $q, $interval, $http) {

    function supported() {
        return 'geolocation' in $window.navigator;
    }

    var retVal = {
        getCurrentPosition: function (options) {
            var deferred = $q.defer();
            if (supported()) {
                $window.navigator.geolocation.getCurrentPosition(
                    function (position) {
                        $rootScope.$apply(function () {
                            this.coords = position.coords;
                            this.timestamp = position.timestamp;
                            deferred.resolve(position);
                        });
                    },
                    function (error) {
                        $rootScope.$apply(function () {
                            deferred.reject({error: error});
                        });
                    }, options);
            } else {
                deferred.reject({
                    error: {
                        code: 2,
                        message: 'This web browser does not support HTML5 Geolocation'
                    }
                });
            }
            return deferred.promise;
        },

        drawMarker: function (lat, lng) {

            map = new google.maps.Map(document.getElementById("map"), mapOptions);

            var marker = new google.maps.Marker({
                position: myLatlng,
                title: "Hello World!"
            });
        }
    };


    // the factory service runs at startup, so the interval will run the whole time the app is running
    $interval(function () {
        retVal.getCurrentPosition().then(function(location) {

            var newLatitude = location.coords.latitude,
                newLongitude = location.coords.longitude;

            // broadcast event
            $rootScope.$broadcast('geolocationCurrentPosition', newLatitude, newLongitude);

            // send data to server
            $http.put(PUT_PATH, {
                "longitude": newLatitude,
                "latitude": newLongitude
            }).then(function (response) {
                console.log('data sended');
            }, function (errorResponse) {
                console.error(errorResponse);
            });
        }.bind(this));

    }, 2000);

    return retVal;
}]);

修改后的控制器:

.controller('geolocationCtrl', [ '$scope', '$http',
    function($scope, $http) {

        // constants should be uppercase
        var GET_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation',
            PUT_PATH = 'https://temp-domain.co.uk/rest/rest.php/client/geolocation/update';


        $http.get(GET_PATH).then(function (response) {
            var respLong = Number(response.data.longitude),
                respLat = Number(response.data.latitude);

            $scope.map = drawMap(respLong, respLat);
            $scope.marker = new google.maps.Marker({
                position: new google.maps.LatLng(respLong, respLat)
            });
            $scope.marker.setMap($scope.map);

        }, function (errorResponse) {
            console.error('error response ' + errorResponse);
        });

        function drawMap(latitude, longitude) {
            var lat = latitude,
                long = longitude,
                currentLatlng = new google.maps.LatLng(lat, long);
            var map = new google.maps.Map(document.getElementById('map'), {
                center: currentLatlng,
                zoom: 10
            });
            return map;
        };

        // listen for the event from geolocationFactory
        $scope.$on('geolocationCurrentPosition', function(event, latitude, longitude){
            // delete old marker
            $scope.marker.setMap(null);
            $scope.marker = new google.maps.Marker({
                position: {
                    lat: latitude,
                    lng: longitude
                }
            });
            var LatLng = new google.maps.LatLng(latitude, longitude);
            $scope.map.setCenter(LatLng);
            $scope.marker.setMap($scope.map);
        });
    }])