Angular.js pass data from async service to scope

前端 未结 4 1203
予麋鹿
予麋鹿 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 12:05

    Try this

    function MainCtrl($scope, geolocation) {
       $scope.city = null;
       geolocation.getCurrentCity(function(city){
           $scope.city = city;
           if(!$scope.$$phase) {
                $scope.$digest($scope);
            }
       });
    };
    

    Sometimes, the watcher is not always called when instanciating the controller, by forcing a digest event, if the scope is not in phase, you can go to where you want to go, I believe. Let me know if I didn't understand your question.

    Oh and I don't know if i read the code properrly but it seems that you're not calling the onSuccess callback in your function: replace your getCurrentCity function by this:

    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;
                    if(typeof onSuccess === 'function') {
                         onSuccess(city);
                    }
                });
            });
        }
    

提交回复
热议问题