StackOverflow_24862225: page-doesnt-redirect-to-the-specified-page-on-invalid-url

Illustration of answer to http://stackoverflow.com/questions/24862225/page-doesnt-redirect-to-the-specified-page-on-invalid-url.

by ExpertSystem

HTML

<script src="https://code.angularjs.org/1.5.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.5.5/angular-route.min.js"></script>
<div>
  <nav>
    <a href="#/home">Home</a><!--
 --><a href="#/page/existing">Somewhere</a><!--
 --><a href="#/page/non-existing">Nowhere</a>
  </nav>
  <hr />
  <ng-view></ng-view>
</div>

<!-- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -->
<!-- Page Footer -->
<small class="footer" ng-controller="FooterCtrl">
  <b>Angular v{{version.full}}</b> ({{version.codeName}})
  <span class="right">
    &copy;
    <a ng-href="{{authorUrl}}" target="_blank">ExpertSystem</a>
  </span>
</small>

CSS

nav a {
  border-right: 2px solid DarkGray;
  padding: 10px;
}

nav a:last-of-type {
  border-right: none;
}

/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
body { padding-bottom: 22px; }
.footer { background-color: White; border-top: 1px solid rgba(100, 100, 100, 0.33); bottom: 0; display: block; font-size: 0.75em; height: 20px; left: 0; margin: 0 10px; overflow: auto; padding: 5px 0; position: fixed; right: 0; }
.right { float: right; }

JavaScript

(function () {'use strict';

angular.
  module('myApp', ['ngRoute']).
  config(configRouteProvider).
  constant('PAGES', constPages());

// Functions - Definitions
function configRouteProvider($routeProvider, PAGES) {    
  $routeProvider.
    when('/', {
      redirectTo: '/home'
    }).
    when('/home', {
      template: '<h1>Home</h1>'
    }).
    when('/page/:pageId', {
      template: function getPageTemplate(routeParams) {
        return '<h1>Page: ' + routeParams.pageId + '</h1>';
      },
      resolve: {
        exists: function resolveExists($location, $route) {
          if (PAGES.indexOf($route.current.params.pageId) === -1) {
            $location.replace();
            $location.path('/error/404');
          }
          return true;
        }
      }
    }).
    when('/error/404', {
      template: '<h1 style="color:Red;">404 - Page Not Found</h1>'
    }).
    otherwise({
      redirectTo: '/error/404'
    });
}

function constPages() {
  var PAGES = [
    'existing'
  ];
  return PAGES;
}

/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
angular.
  module('myApp').
  controller('FooterCtrl', function FooterCtrl($scope) {
    $scope.authorUrl = '//stackoverflow.com/users/2341938/expertsystem';
    $scope.version = angular.version;
  });

}());