Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

AngularJS ui router html5mode

Suggested Videos
Part 46 - Case sensitivity with angularjs ui-router
Part 47 - Angular ui router default route
Part 48 - AngularJS ui router custom data



In this video we will discuss how to configure HTML5 mode routing in an angular application that is using ui-router.



The steps required to configure HTML5 mode routing are same whether you are using ngRoute or ui-router. In Part 27 of AngularJS tutorial we have already discussed how to configure HTML5 mode routing for ngRoute. 

Step 1 : Enable html5mode routing. To do this inject $locationProvider into config() function in script.js and call html5Mode() method passing true as the argument value.

var app = angular
            .module("Demo", ["ui.router"])
            .config(function ($locationProvider) {
                $locationProvider.html5Mode(true);
            })

Step 2 : Remove # symbols from the URLs if there are any. In the sample application that we have been working with, does not have any # symbols as we have used ui-sref attribute instead of href attribute to create links.

Step 3 : Include the following URL rewrite rule in web.config. This rewrite rule, rewrites all urls to index.html, except if the request is for a file, or a directory or a Web API request. 

<system.webServer>
  <rewrite>
    <rules>
      <rule name="RewriteRules" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Step 4 : Set the base href to the location of your single page application. In the head section of index.html include the following line.
<base href="/" />

Important : Place the <base href="/" /> element just below the <titleelement in the head section of index.html page. Otherwise the application does not work as expected when you refresh the student details page.

With all the above changes HTML5 mode routing should work as expected. Notice all the URLs are clean without any # symbols.

AngularJS tutorial for beginners

1 comment:

  1. Hi Venkat,
    Thanks for sharing Important note about base href at the end of tutorial. Many developers may stuck at this point.

    ReplyDelete

It would be great if you can help share these free resources