javascript - Angular: how to handle both HTML5 mode routes and hash routes? -
i've been using "standard" routes in angular 1 use # sign (e.g. /app#/home). switch html5 mode have pretty urls (e.g.: /app/home).
i've toggled html5 mode $locationprovider.html5mode(true) , working expected.
however, of our users may still have bookmarks , links in email have old url format , break. have old urls still work (have /app#/home redirect /app/home automatically).
i've tried having default route looks @ hash so:
$routeprovider .when({ ... }) .otherwise({ 'controller': function($location) { var hash = $location.hash(); // @ point hash undefined (even when there 1 in url) console.log('hash = ' + hash); // if (hash && hash.indexof('/') == 0) { // $location.path(hash); // } else { // $location.path('/home') // } } }); that unfortunately did not work (the controller doesn't see hash , angular seems go in infinite digest loop).
any idea on how achieve that?
use $routechangestart :
angular.module('routing', ['ngroute']) .run(['$rootscope', '$location', '$window', function($rootscope, $location, $window) { $rootscope.$on("$routechangestart", (event, current, previous, rejection) => { if (/#\//.test($window.location.hash)) { $location.path($window.location.hash.replace('#', '')); } }); ...
Comments
Post a Comment