How to redirect to home view after page refresh – AngularJS

All we need is an easy explanation of the problem, so here it is.

Question Background:

I have encountered what seems to be a common issue with AngularJS where I am implementing:

 $locationProvider.html5Mode({ enabled: true, requireBase: false });

This has removed the ‘#’ from my URL routes and in-turn caused a 404 error. I fixed that by adjusting web.config and the page reloads now.

The Issue:

I have a 2 views called Home.html and Results.html. I also have a index.html which houses the in my app which houses a <div ui-view> where the home and result views are injected into.

The following is the routes used:

http://localhost:5XXXX/ - home
http://localhost:5XXXX/results - results

I want to redirect to the home.html view when results.html is refreshed. Currently when results.html is refreshed all of y scope data is lost along with jquery plugin object state in the directives.

The Code:

app.js – this houses the routes of the app:

 angular
  .module('app', [
    'ui.router',
    'ui.bootstrap',
    'ngAnimate',
    'ngResource',
    'rzModule',
    'angular-ladda',
    'jcs-autoValidate'
  ])
  .config(['$urlRouterProvider', '$stateProvider', '$locationProvider', function ($urlRouterProvider, $stateProvider, $locationProvider) {

      $urlRouterProvider.otherwise('/');
      $stateProvider
        .state('home', {
            url: '/',
            templateUrl: 'home.html',
            controller: 'HomeController'
        })


          $stateProvider.state('results', {
              url: '/results',
              templateUrl: 'Results.html',
              controller: 'ResultsController'
          })

          $locationProvider.html5Mode({
              enabled: true,
              requireBase: false
          });
    }]);

ResultsController.js:

var app = angular.module('app');

app.controller('ResultsController', function ($scope, $rootScope, $timeout, $location, $anchorScroll, $window, searchService) {

    //code

});

If I refresh the Results.html page how can I immediately redirect to the Home.html view instead of reloading the Results.html page?

EDIT:

I have updated the ResultsController.js with the following but this code does not seem to be called on a reload, it does not redirect to home.

var app = angular.module('app');

app.controller('ResultsController', function ($scope, $rootScope, $timeout, $location, $anchorScroll, $window, searchService) {

    $rootScope.$on('$locationChangeStart', function (event) {
        $state.go('/');
    });
});

Also to add I have added the following to the Web.config of my app to handle rerouting:

<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Use $locationChangeStart

$rootScope.$on('$locationChangeStart', function(event) {
   $state.go('/');
});

Proper code : $locationChangeStart run
Put this in main app file and attach it to app like app.config do it like app.run()

.run(['$rootScope', '$state', function($rootScope, $state, userService) {
       $rootScope.$on("$locationChangeStart", function(event, next, current) {
          if(next == current) {
                event.preventDefault();
                $state.transitionTo('/');
            }
       });
}]);

Method 2

some pseudo code

var app = angular.module('app');
app.controller('ResultsController', function ($scope, $rootScope, $timeout, $location, $anchorScroll, $window, searchService, $state) {
  if (data unavailable) {
    $state.go('home');
  }
});

if your results data isn’t available just do $state.go(‘home’); in the ResultsController

Method 3

Looks like that’s been answered here: How to redirect on different view on refresh in AngularJS?

$rootScope.$on("$locationChangeStart", function(event, next, current) { 

if(next==current && next=='/results')
    event.preventDefault();
    $state.go('home');
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply