1

I know there is no catchall controller for Angular. E.g.:

 $routeProvider.otherwise({
 controller: 'CatchAllCtrl'
 });

However, is there a way to call some code if $routeProvider.otherwise is triggered so I can at least know that otherwise was called and what the route was?

JStark
  • 2,788
  • 2
  • 29
  • 37

3 Answers3

2

You could redirect to a catchcall route, which could execute your "otherwise" logic, and then manually redirect to an actual view in your app.

$routeProvider
  .when('/', {
    templateUrl: '/partials/index.html', 
    controller: 'homeController'
  })
  .when('/otherwise', {
    controller:  'otherwiseController'
  })
  .otherwise({redirectTo: '/otherwise' });

In your otherwiseController, you can inject $location and then set $location.path("/") to redirect to wherever you want to go.

You might need to specify a templateUrl for the /otherwise route (I'm not sure).

CJ Cenizal
  • 197
  • 6
  • Hi CJ, I updated my question to clarify I also need to know what the route was. If you look at $location.$$path it is set to '/otherwise' which doesn't help. – JStark Oct 21 '13 at 23:00
1

You could listen to a route change and perform the required action in the callback.

  $rootScope.$on('$routeChangeSuccess', function() {
    var path = $location.path();
     // this shoudl fire for all routes
  }):
orange
  • 7,755
  • 14
  • 75
  • 139
  • This looks promising, but I'm particularly interested in a fresh page when the user pastes in the URL and isn't in an existing controller. Also, I wouldn't want to paste that code into every controller. It seems config doesn't accept $rootScope. Is there a central place where your example can be called? – JStark Oct 21 '13 at 22:45
  • put it in a service then – xavier.seignard Oct 21 '13 at 23:03
  • You just need to have this code executed once. No need to put it into every controller... – orange Oct 22 '13 at 06:51
0

Kind of a Angular newbie here, so take everything with salt :)

Can't you simply put the code you want to be executed on "otherwise" inside the "CatchAllCtrl"?

Or maybe, you can update a control variable whenever you reach "otherwise" and use the $scope.watch to catch it's change How do I use $scope.$watch and $scope.$apply in AngularJS?

Community
  • 1
  • 1
domokun
  • 3,013
  • 3
  • 29
  • 55