John Smith John Smith - 10 days ago 6
AngularJS Question

Removing # my angularjs pages do not work

I learn angularjs after a tutorial and I saw that you can remove # from the link. I did that but then my partials(from templateUrl) did't come in the page anymore.
Can someone please tell me where I'm wrong?



angular.module('myApp', ['ngRoute'])
.controller('mainController', ['$scope', '$location', '$log', function($scope, $location, $log) {

$log.info($location.path());


}])
.controller('secondController', ['$scope', '$location', '$log', function($scope, $location, $log) {

$log.info($location.path());


}])
.config(function($routeProvider, $locationProvider) {
// $routeProvider lets us specify routes
$routeProvider
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/second', {
templateUrl: 'pages/second.html',
controller: 'secondController'
});
$locationProvider.html5Mode(true);
});

<!DOCTYPE html>
<html lang="en-us" ng-app="myApp">
<head>
<title>Learn and Understand AngularJS</title>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<base href="/">
<!-- load bootstrap and fontawesome via CDN -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<style>
html, body, input, select, textarea
{
font-size: 1.05em;
}
</style>

<!-- load angular via CDN -->
<script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script>
<script src="//code.angularjs.org/1.3.0-rc.1/angular-route.min.js"></script>
<script src="angularjs-learn-understand/ch05/app.js"></script>
</head>
<body>

<header>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">AngularJS</a>
</div>

<ul class="nav navbar-nav navbar-right">
<li><a href="#"><i class="fa fa-home"></i> Home</a></li>
<li><a href="#/second"><i></i> Second</a></li>
</ul>
</div>
</nav>
</header>

<div class="container">

<div ng-view></div>

</div>

</body>
</html>





main.html:

<h1>This is Main.</h1>


second.html

<h1>This is second.</h1>


So in my browser I don't get main.html and second.html when I click on Home and Second. Why?

Answer

The UI Router github docs mentions:

When you have html5Mode enabled, the # character will no longer be used in your urls. The # symbol is useful because it requires no server side configuration. Without #, the url looks much nicer, but it also requires server side rewrites.

When you are trying to access your app in html5Mode (routes without any hash) then first of all you would need to remove the "#" from each one of your links (in this case the links are: Home, Second).

So...

  • "#" would just be "/"
  • "#/second" would be "/second"

After this, you would also need to enable server side URL Rewrites. Please checkout this link and configure your server as per the server that you are using.

Comments