Skip to content

Instantly share code, notes, and snippets.

@graphnode
Last active August 29, 2015 14:06
Show Gist options
  • Save graphnode/5d95219af9272a0638b1 to your computer and use it in GitHub Desktop.
Save graphnode/5d95219af9272a0638b1 to your computer and use it in GitHub Desktop.
Show Not Found (404) page without changing URL using ui-router.
angular.module('Application', ['ui-router'])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
// Create states for application plus on for the error state.
// Notice that the error state doesn't have url (but it can).
$stateProvider
.state('login', {
url: '/login',
templateUrl: '/Login.html',
controller: 'LoginController'
})
.state('dashboard', {
url: '/dashboard',
templateUrl: '/Dashboard.html',
controller: 'DashboardController'
})
.state('error', {
templateUrl: '/Error.html'
})
// The usual code to catch any url but instead of a string ("/ntofound") we use a function
// which receives $injector and $location.
// We could check which URL the user wanted using $location but in this case we are going
// to simply send them to the error state.
// We then tell the provider that we handled the request.
$urlRouterProvider.otherwise(function ($injector, $location) {
$injector.invoke(['$state', function ($state) { $state.go('error'); }]);
return true;
});
// Note: We could have passed parameters to the state (like the URL) and the error state
// controller could have handled them.
}]);
@ertrzyiks
Copy link

Using $ prefixed names when you do not have dependency injection may be misleading. I think it would be better with:

$urlRouterProvider.otherwise(function (injector, location) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment