$scope push doesn't work angularjs

447 views Asked by At

I have an issue with this code.

In my controller I have this.

$scope.spiagge = [];
var distanza = function(info, posizione) {
        var request = {
            origin : posizione,
           destination : new google.maps.LatLng(info.latitudine, info.longitudine),
           travelMode : google.maps.TravelMode.DRIVING
       };
       directionsService.route(request, function(response, status) {
           if (status == google.maps.DirectionsStatus.OK) {
               //$scope.directionsDisplay.setDirections(response);

               info.distanza = response.routes[0].legs[0].distance.text;

               //distanza= response.routes[0].legs[0].distance.value/1000 ;
           }

        riempi(info);

    });
//riempi(info);
}
var riempi = function(spiaggia) {
    //alert("distanza " + spiaggia.distanza);
    $scope.spiagge.push(spiaggia);
}

If I put riempi(info) outside the directionsService function, $scope.spiagge.push works without info.distanza. I think this is because info.distanza is a local variable of directionService . If I put inside, like in the code here, it doesn't work at all; but the riempi function sees every value of info, distanza included.

I don't know what to do. This is the view

<div class="lista_home" ng-repeat= "spiaggia in spiagge">
    <h1>{{spiaggia.nome}}</h1> <p>distanza {{spiaggia.distanza}} km </p>
  </div>

Sorry for my english. Any idea?

Thanks.

2

There are 2 answers

0
Hoyen On BEST ANSWER

Since googlemaps isn't ummm... 'angular' the view won't update. Can you try adding $scope.$apply(); at the end of your $scope.riempi function?

0
Michelangelo On

What I think that happens is that when it is inside the directionService the function is out of scope. You can try to reach the function with $rootScope. Instead of making a variable add it the function to the scope of the controller. Also don't forget to inject $rootScope as a dependency in your controller.

$scope.spiagge = [];
    var distanza = function(info, posizione) {
            var request = {
                origin : posizione,
               destination : new google.maps.LatLng(info.latitudine, info.longitudine),
               travelMode : google.maps.TravelMode.DRIVING
           };
           directionsService.route(request, function(response, status) {
               if (status == google.maps.DirectionsStatus.OK) {
                   //$scope.directionsDisplay.setDirections(response);

                   info.distanza = response.routes[0].legs[0].distance.text;

                   //distanza= response.routes[0].legs[0].distance.value/1000;
               }

            $rootScope.riempi(info);//go to the rootscope and find riempi

        });

    }
    $scope.riempi = function(spiaggia) {
        //alert("distanza " + spiaggia.distanza);
        $scope.spiagge.push(spiaggia);
    }