Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the hash # from the angularjs ng-route

I am trying to use the locationProvider to remove the hashtag from the url routes in angular js but it gives me error.

app.js

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

eclassApp.config(['$routeProvider','$locationProvider',
    function ($routeProvider, $locationProvider){
        $routeProvider.
            when('/',{
                templateUrl: '/html/student-list.html',
                controller: 'StudentsListCtrl',
            }).
            when('/students/:studentId',{
                templateUrl: '/html/student-details.html',
                controller: 'StudentDetailsCtrl',

            }).otherwise({
                redirectTo: '/students'
            });
            $locationProvider.htmlMode(true);
    }]
);

the error:

 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=eclassApp&p1=TypeE…oogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.3.13%2Fangular.min.js%3A17%3A1)

Am I missing something?

EDIT: calling the html5Mode function with options object like this

$locationProvider.html5Mode({
    enabled:true
})

i get the following error (changed to angular full to get a better explanation of the error istead of the minified version)

Error: [$location:nobase] $location in HTML5 mode requires a <base> tag to be present!

http://errors.angularjs.org/1.3.13/$location/nobase

like image 610
Apostolos Avatar asked Feb 20 '15 13:02

Apostolos


People also ask

What does hash in URL mean?

In a URL, a hash mark, number sign, or pound sign ( # ) points a browser to a specific spot in a page or website. It is used to separate the URI of an object from a fragment identifier. When you use a URL with a # , it doesn't always go to the correct part of the page or website.

What does Window location replace do?

Window location. The replace() method replaces the current document with a new one.


2 Answers

you can use the $locationProvider like this -

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

Alternatively, you can use the base tag in your index.html (I suppose this is your landing page)

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

Removing base tag may cause some side effects in old IE browser like IE9

like image 101
Rabi Avatar answered Oct 05 '22 11:10

Rabi


Steps to get rid of # from URL:

  1. Inject $locationProvider in config() function of angular root module and set html5Mode() to true

    angular.module( 'app', [ ] ).config(function( $locationProvider) {
       $locationProvider.html5Mode(true);
    });
    
  2. Include base tag in head section of first loading page of application..

like image 30
Giridhar Kumar Avatar answered Oct 05 '22 13:10

Giridhar Kumar