Search code examples
jqueryangularjsreactjssingle-page-applicationsammy.js

Single page app url management


Usually in a Single Page App(spa), I do have a single page have where I have a sidenav menu. In that menu, there are multiple anchor tags.
Those anchor tag's url will be handled by angular/react/sammy js router, and the main div would be refreshed based on the returned html from the controller.
Pretty simple, right?
But imagine a scenario, where user directly access the anchor tag url via browser address bar. then only the returned html segment would be loaded to the whole page.
Is there any way to handle this kind of situation; I mean so that whenever user directly access the url, he/she would be properly addressed?

EDIT: May be I'm not so clear about the problem statement. Let me elaborate a bit:

  • Suppose my page url is: abc.com/dashboard
  • This page got a navigation menu and a div section whose class name is "main-container"
  • User click a link in the nav menu and the router moved the url to for say abc.com/view/listofXYZ. So, our "main-container" div would be loaded with the response of the url abc.com/view/listofXYZ
  • Now another user, directly go to the abc.com/view/listofXYZ url and hit eneter. Then, the page would contain only the response html of the url i.e. all nav menu and div are gone.


My question is, can we implement some design approach, so that these two works well?


Solution

  • Better go for angular ui-router instead of sammy js router, Of course I don't know about it. But in angular-ui-router, we define states and urls by using $stateProvider of ui-router. Even user entered the url directly in the browser, he wil be addressed correctly only if the url defined in the state matched.

    https://github.com/angular-ui/ui-router/tree/legacy see here for more info.

    Here is an example,

    $stateProvider.state('',{
       url: '/',
       tempate: 'path/to/.html',
       controller: 'controllerToHandle'
    })
    .state('home', {
       url: '/home',
       template: 'path/to/home.html',
       controller: 'HmeCtrl'
    })
    .state('home.list',{  //defines child states with dot
       url: '/list', //shows url as home/list because it is a child state
       template: 'path/to/list.html'
    })
    

    Use $urlRouterProvider.otherwise('/') if no path matched Likewise, user can traverse from home to list for example, www.my-app.com is your host name. If he entered www.my-app.com/home/list as url /home/list matched, he will be taken to home/list page and if he entered any wrong url, then he will be taken to home page because of otherwise method.

    If there is something like this in the react/sammy router, do that for better solution