An example to create a single page application without any page refreshes using Angular’s routing capabilities.
We will be using
$routeProvider
in Angular to handle our routing. Angular will handle to go get a new file and inject it into our layout.
Define the routes with
$routeProvider
. Configure to specify the route, the template file to use, and controller. This way, each part of our application will use its own view and Angular controller.
script.js
Create the module and name it
rookieApp also include ngRoute for all our routing needs.
var rookieApp = angular.module('rookieApp', ['ngRoute']);
Configure our routes
snippet
rookieApp.config(function($routeProvider) {
$routeProvider
// route for the home page
.when('/', {
templateUrl: 'pages/home.html',
controller: 'mainController'
})
// route for the about page
.when('/about', {
templateUrl: 'pages/about.html',
controller: 'aboutController'
})
// route for the contact page
.when('/contact', {
templateUrl: 'pages/contact.html',
controller: 'contactController'
});
});
Create the controller and inject Angular's $scope
snippet
rookieApp.controller('mainController', function($scope) {
// create a message to display in our view
$scope.message = 'Everyone come and see how good I look!';
});
rookieApp.controller('aboutController', function($scope) {
$scope.message = 'Look! I am an about page.';
});
rookieApp.controller('contactController', function($scope) {
$scope.message = 'Contact us! JK. This is just a demo.';
});
Clean URLs
By default, Angular will append a hash
(#) into the URL.To get rid of this, we will need to use
$locationProvider
to enable the HTML History API.This will remove the hash and make pretty URLs.
Our home page will pull the
home.html file. About and contact will pull their respective files. Now if we view our app, and click through the navigation, our content will change.
snippet
<!-- home.html -->
<div class="jumbotron text-center">
<h1>Home Page</h1>
<p>{{ message }}</p>
</div>
<!-- about.html -->
<div class="jumbotron text-center">
<h1>About Page</h1>
<p>{{ message }}</p>
</div>
<!-- contact.html -->
<div class="jumbotron text-center">
<h1>Contact Page</h1>
<p>{{ message }}</p>
</div>
Routing on local environment
Angular routing will only work in the web server. Make sure you are using
http://localhost or some sort of environment. Otherwise Angular will spit out a Cross origin requests are only supported for
HTTP.