2

我正在使用带有phonegap的angular.js。为了获取用户 gps 位置,我开发了一个简单的服务:

app.factory('geolocation', function ($rootScope, cordovaReady) {
    return {
        getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {

            navigator.geolocation.getCurrentPosition(function () {
                var that = this,
                    args = arguments;

                if (onSuccess) {
                    $rootScope.$apply(function () {
                        onSuccess.apply(that, args);
                    });
                }
            }, function () {
                var that = this,
                    args = arguments;
                if (onError) {
                    $rootScope.$apply(function () {
                        onError.apply(that, args);
                    });
                }
            }, options);
        });
    }
});

我这样称呼这项服务

geolocation.getCurrentPosition(function (position) {
   console.log(position);
});

现在我想使用另一种名为getCurrentCity的方法来扩展服务。此方法应使用getCurrentPosition来确定城市。所以服务看起来像这样:

app.factory('geolocation', function ($rootScope, cordovaReady) {
    return {
        getCurrentPosition: ....
        getCurrentCity: ...
    }
});

这可能吗?我应该如何使用 getCurrentPosition 来实现 getCurrentCity?

4

1 回答 1

1

如果我在这里回答错误的问题,请原谅我,但如果您只是问如何从服务返回多个方法,那很简单:

angular.module('app', []).factory('geolocation', function ($rootScope, cordovaReady) {
    var locationObj = {
        getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {

            navigator.geolocation.getCurrentPosition(function () {
                var that = this,
                    args = arguments;

                if (onSuccess) {
                    $rootScope.$apply(function () {
                        onSuccess.apply(that, args);
                    });
                }
            }, function () {
                var that = this,
                    args = arguments;
                if (onError) {
                    $rootScope.$apply(function () {
                        onError.apply(that, args);
                    });
                }
            }, options);
        }),

        getCurrentCity: function() {
            this.getCurrentPosition(function(position){
                //determine city
                var city = ...
                //how to apply city to scope?
            });
        }
    }

    return locationObj;
});

如果您要询问特定于 phonegap 的问题,请忽略!

于 2013-07-16T17:43:31.727 回答