AngularJS is a powerful javascript framework introduced to make several tasks easier in javascript. AngularJS extends HTML with new attributes which are with "
ng" prefix
. AngularJS is especially designed to create SPA's (Single Page Applications). SPA is a type of application in which user can view partial template (separate views) without page reload. This makes the application more quick & faster.
SPA's or Single Page Applications are built using Routing service of AngularJS. This service allows you to access different pages without page reload. By default, SPA's built with angularJS have a # in the URL which usually annoys develpers. The tutorial is about how you can get rid of this problem.
Let's have a look at the below HTML code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.2/angular-route.min.js"></script>
</head>
<body>
<a href="#main">Main Page</a>
<a href="#contact">Contact Page</a>
<a href="#about">About Page</a>
<ng-view>
<!--Partial templates go here..-->
</ng-view>
</body>
</hmtl>
In our above HTML code, we've linked angular.min.js & angular-route.min.js. Linking angular.min.js is must to work with angularJS & angular-route.min.js is must to use routing service of angularJS otherwise routung wouldn't work. In body area, we've included ng-view element to put partial views inside (Container for partial views).We've also added some links to navigate to pages.
We have some JS code as under:
<script>
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl : 'views/main.html',
})
.when('/contact', {
templateUrl : 'views/contact.html'
})
.when('/about', {
templateUrl : 'views/about.html'
})
.when('/courses', {
templateUrl : 'views/courses.html'
})
.otherwise({
redirectTo : '/'
});
});
</script>
In the above JS code, we've written some code to make our application 'Single Page' using
routing service of angularJS (we are not going in detail).
This result will be that your application would work fine but the URL will look like this:
http://localhost/angularJS/#/main
But we don't want it so. To remove the
# form the URL, pass
$locationProvider as dependency to
config object:
app.config(function($routeProvider, $locationProvider)
Enable HTML5 Mode to remove the
#. Write the following code:
$locationProvider.hashPrefix(''); //This will remove !
$locationProvider.html5Mode(true); //This will remove #
below
app.config(function($routeProvider, $locationProvider){
Also remove
# from links in HTML. (#main, #contact, #about).
Now, your url will look like this:
http://localhost/angularJS/main
Hope this tutorial helps you.
Always be happy