April 13, 2016

$locationProvider in angular js

$locationProvider in angular js

It is very easy to get clean URLs and remove the hashtag from the URL. It is done by configuring $locationProvider and setting our base for relative links.

By default, AngularJS will route URLs with a hashtag. For example:

http://website.com/
http://website.com/#/about
http://website.com/#/contact

$location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

$locationProvider and html5Mode

We will use the $locationProvider module and set html5Mode to true.

We will do this when defining your Angular application and configuring your routes.

var app = angular.module('app', ['ngRoute']);

app.config(function($routeProvider, $locationProvider) {
   $locationProvider.html5Mode(true);
   $routeProvider
      .when('/', {
         templateUrl: "partials/home.html",
         controller: "HomeCtrl"
        })
      .when('/page1', {
         templateUrl: "partials/page1.html",
         controller: "Page1Ctrl"
      })
      .when('/page2', {
         templateUrl: "partials/page2.html",
         controller: "Page2Ctrl"
      })
      .otherwise({
         redirectTo: "/"
      })
});

Setting For Relative Links

To link around your application using relative links, you will need to set a <base> in the <head> of your document.

<!doctype html>
<html>
<head>
   <meta charset="utf-8">

   <base href="/">
</head>

This is a simple way to get pretty URLs and remove the hashtag in your Angular application.

No comments:

Post a Comment

Popular Posts

Views