1

In AngularJS, is there a way to intercept a route change that is not defined in the routeProvider so the route can be looked up in the database and, if a valid match in the database, the new route can be added to the routeProvider?

I've read it is possible to add, dynamically, a route, but I need to do it when the current route has no match.

MaryJosie
  • 13
  • 2
  • 1
    Take a look at this: http://stackoverflow.com/questions/13153121/how-to-defer-routes-definition-in-angular-js/13173667#13173667 – nweg Apr 20 '15 at 20:29
  • Thanks, I've read that it is possible to add, but I need to capture the event or the point in the lifecycle of routing that the angular engine did not find a match so I can plug in code to handle the unmatch. – MaryJosie Apr 20 '15 at 21:01

2 Answers2

0

Assuming you can do it in controller, you can capture this event as following:

$rootScope.$on("$routeChangeSuccess", function (event, next, current) {
    if(!angular.isDefined($route.current.$$route))
      addDynamicRoute('using techniques mentioned above'); 
    else
      handleOtherStuff();
});
ABOS
  • 3,723
  • 3
  • 17
  • 23
0

I would have used the otherwise method of $routeProvider to load a predefined page (controller) to handle undefined routes.

otherwise({
    templateUrl: 'addRoute.html',
  });

And then, into this controller, get the current route requested using $location ($location.url()). Add this route dynamically if needed :

$route.routes['/new'] = {templateUrl: 'new.html'};

Finally, redirect to this route using :

$location.path('/new');

Obviously, for this to work you will need to inject $route and $location as dependency to your controller.

gosp
  • 76
  • 4
  • This method worked perfectly for me. I was able to use the $location.path() in the controller associated in the otherwise option like you've mentioned and look up in the database if a new page between the time they downloaded the initial routes to this point. I did have to use $route.refresh() instead of $location.path('/new'). The current path was already '/new' so the new route didn't load. – MaryJosie Apr 21 '15 at 02:23
  • I also want to mention that I added the routes via http://stackoverflow.com/a/22496387/2857047 as the $route.routes['/new'] method above didn't work in v1.3.* – MaryJosie Apr 21 '15 at 02:25