Angular.js pass data from async service to scope

前端 未结 4 1205
予麋鹿
予麋鹿 2020-12-13 11:20

I have a service like

app.factory(\'geolocation\', function ($rootScope, cordovaReady) {
    return {
        getCurrentPosition: cordovaReady(function (onSu         


        
4条回答
  •  执笔经年
    2020-12-13 11:53

    You are dealing with callbacks and asynchronous request. So you should use $q service. Just inject it in your service with $rootScope and cordovaReady dependency. And add the promises to your function like this

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

    And in your controller, do the following to handle the 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
       });     
    };
    

提交回复
热议问题