我有类似的服务
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); }), getCurrentCity: function (onSuccess, onError) { this.getCurrentPosition(function (position) { var geocoder = new google.maps.Geocoder(); geocoder.geocode(options,function (results, status) { var city = address_component.long_name; }); }); } } });
我想从控制器做类似
function MainCtrl($scope, geolocation) { geolocation.getCurrentCity(function(city){ $scope.city = city; }); };
getCurrentPosition可以正常工作,并且城市也已确定,但是我不知道如何在控制器中访问城市。
怎么了? 调用getCurrentCity时,它将调用getCurrentPosition来确定gps坐标。该坐标作为参数传递给onSuccess方法,对吗?因此,这与我要在getCurrentCity方法中执行的操作完全相同,但我不知道如何做。异步地理编码器检索了城市,我想将新数据应用于onSuccess方法。
有任何想法吗?
您正在处理回调和异步请求。因此,您应该使用$ q服务。只需使用$ rootScope和cordovaReady依赖项将其注入您的服务即可。并像这样向您的功能添加承诺
getCurrentCity: function () { var deferred = $q.defer(); this.getCurrentPosition(function (position) { var geocoder = new google.maps.Geocoder(); geocoder.geocode(options,function (results, status) { var city = address_component.long_name; $rootScope.$apply(function(){ deferred.resolve(city); }); }); }); return deferred.promise; }
然后在您的控制器中,执行以下操作来处理承诺。
function MainCtrl($scope, geolocation) { geolocation.getCurrentCity().then(function(result) { //result === city $scope.city = result; //do whatever you want. This will be executed once city value is available }); };