mtfurlan mtfurlan - 3 months ago 28
AngularJS Question

Angular change route and then call function in that controller

So I have two routes, one of which is a leaflet map. I have a socket.io thing running, giving the map pins, and I have toast notifications on both views when a new pin is added.

When a user clicks on a toast, it should zoom to the location of that pin, but I only know how to implement that when I'm already in the map controller.

How do I approach this problem? As I see it, I need to switch routes and call a function in the new controller with an argument, which doesn't seem possible.

My route config, in the main module.

.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/chat', {
templateUrl: 'chat/chat.html',
controller: 'ChatCtrl',
controllerAs: 'chat'
})
.when('/map', {
templateUrl: 'map/map.html',
controller: 'MapCtrl'
})
.otherwise({redirectTo: '/map'});
}])

Answer

You can use ng-href to set the url for an anchor inside the toast that the user clicks.

<a ng-href="#/map/{{pinId}}" />

Then when the user clicks that it will route them to the map path. In the controller you should inject $routeParams to check whether a param is set and if so to them zoom the user to that pin.

Comments