Angular Dynamic Menu and Initial URL

There was one small problem I solved (elegantly I think) today that I wanted to share.  When I navigate to a URL into my Angular app, I want to make sure the URL is retained after my routes are built after the login process.  This issue came up because I build my routes after I login, so the initial URL is lost as part of navigation to login route I talked about here.  Login route is the only one that exists initially.

To get around the issue I want to save the initial URL.  I do that in my main entry module, app module.  To do that I add run() block.  I inject two things into it: location server and root scope service.  I need the former to obtain current / initial path.  I need the latter to save this path for future use.

        .run(['$location', '$rootScope', function ($location: ng.ILocationService, $rootScope: ng.IRootScopeService) {
            $rootScope['startPath'] = $location.path();

The code is in TypeScipt, but you can just delete the types to get JavaScript version.  Now, I need to update my home controller that kicks in after the login process in “routes loaded” event handler.

$scope.$on('loggedIn', () => {
                menuService.getMenu((menu: IMenuItem[]) => {
                    $scope.menuItems = menu;
                    $rootScope.$on('routesLoaded', () => {
                        if ($rootScope['startPath']) {
                        } else {
                    $rootScope.$broadcast('menuLoaded', menu);

As you can see, if I have an initial path, I navigate to it.  Otherwise I use blank path, forcing the app to go to the default route, which is ‘/home’ in my case. 

Easy yet effective and clean.


One Comment

  1. Pingback: Building Dynamic Menu with Angular JS, Web Api and ASP.NET MVC | Sergey Barskiy's Blog

Leave a Reply

Your email address will not be published. Required fields are marked *