Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

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) {

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. 

      <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" />
        <action type="Rewrite" url="/index.html" />

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

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.