1

In my angular app I am trying to change the location to "#home" when the user enters an invalid route.

Here's a short but complete app demonstrating what I did.

<!DOCTYPE html>
<html>
<head>
    <script src="angular.js"></script>
    <script>
        angular.module('app', [])
        .controller('ctrl', function($scope, $location, $window) {
            $scope.$watch (function() { return $location.url() }, function(url) {
                if (url == '')
                    $window.location = '#home'
            })
        })
    </script>
</head>
<body ng-app="app" ng-controller="ctrl"></body>
</html>

But when I do this I get an infdig error when the page loads. I don't know whats wrong.

Edit: I don't want to use routing libraries like "ui-router". so answers like this one that uses the "angular-route" library are not helpful.

Community
  • 1
  • 1
Ali Dorosty
  • 149
  • 2
  • 10
  • possible duplicate of [How to watch for a route change in AngularJS](http://stackoverflow.com/questions/14765719/how-to-watch-for-a-route-change-in-angularjs) – Rahil Wazir May 24 '15 at 12:33

1 Answers1

3

You can specify that in app.config block using $routeProvider.

app.config(function ($routeProvider) {
  $routeProvider
    .when('/home', {
      template: 'home.html',
      controller: 'homeController'
    })
    .otherwise('/home');
});

.otherwise method will redirect the application to /home, if user tries to access any invalid path which is not specified in config.


Update:

And, If you don't want to use angular routing library you can use native javascript event hashchange on window to listen for hash change events. and redirect accordingly.

see the below example.

function locationHashChanged() {
  if (location.hash !== "#/home") {
    console.log('hash is other then #home. will redirect to #home');
    console.log('Full path before', document.URL);
    window.location.hash = '#/home';
    console.log('Full path after', document.URL);
  }
}

window.addEventListener('load', locationHashChanged);
window.addEventListener('hashchange', locationHashChanged);
<a href="#home">Home</a>
<br/>
<a href="#somesite">Some-Site</a>
<br/>
<a href="#other">Other</a>
jad-panda
  • 2,509
  • 16
  • 22
  • I think for plain javascript we could use something simple like this, window.onhashchange = function() { var key=window.location.hash; console.log(key); switch(key){//do your thing} } – Prem Santh Nov 17 '18 at 14:00