angularjs - Angular: Changing path inside event handler not working -


i'm new angular, , having problem changing location inside of event handler. handler marker positioned on google map. using ng-map (which pretty awesome).

here's code creates markers (this runs inside success callback of $http get):

for( = 0; < data.pins.length; i++ ) {     var marker = new google.maps.marker({         title: data.pins[i].streetaddress,         position: new google.maps.latlng(data.pins[i].latitude,data.pins[i].longitude),         data: data.pins[i],         index: i,     });      google.maps.event.addlistener(marker, 'click', function(tgt) {         $scope.pinclicked(marker);     });      marker.setmap($scope.map);      $scope.markers.push(marker); } 

the event handler simple:

$scope.pinclicked = function(marker) {     if( marker.data.homes.length == 1) $location.path("/home");     else $location.path("/unit"); }; 

when click on marker handler executes, , if/then/else statement executed. however, location not change.

is because i'm outside "context" angular because set event listener through google maps?

additional info

thanx suggestion using window.location. didn't mention earlier map part of partial view, don't want trigger page reload -- want angular update partial view based on location change. know can do, because $location.path('/unit') works fine outside of event handler.

the problem google maps event callback runs outside angular context. calling $location.path("...") correct (you should not use window.location in angular app), must use location service within callback that's under angular's control. that's not happening here. consider excerpt code:

$http.get(..., function() {   (i = 0; < data.pins.length; i++) { // loop      ...     google.maps.event.addlistener(marker, 'click', function(tgt) {       $scope.pinclicked(marker);     }); 

the $http.get() callback (your function) fires within angular context; when function returns, angular triggers $digest cycle, updates bindings. it's $digest cycle process $location changes.

however... callback google.maps.event.addlistener fires later, outside angular context. angular won't see scope changes or $location changes make within callback (at least, not immediately—not until next time $digest cycle happens run, whenever is).

you need wrap call $scope.pinclicked(marker) within $scope.$apply, so:

google.maps.event.addlistener(marker, 'click', function(tgt) {   $scope.$apply(function() {     $scope.pinclicked(marker);   }); }); 

by wrapping call in $scope.$apply, you've told angular, "hey, run code in function, , kick off $digest cycle."


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -