Handling AngularJS Routing with Angular-Route (ngRoute)

Dale Nguyen
ITNEXT
Published in
3 min readAug 7, 2018

--

I started with Angular 2+, but my current company has some projects that require AngularJS 1x. So, here we are!

I this post, I will show you how to handle AngularJS 1x routing by using Angular-Route (ngRoute). There will be another post that I will use UI-Router for handling AngularJS routing.

The different between two of them is that UI-Router is a 3rd-party module that uses a different approach to manage routing, and UI-Router has extra features and suitable for more complicated projects.

If you want to read more about the different between two of them, please check this thread from stackoverflow.

The AngularJS version that I used in this post is 1.7.2, it may different if you use older versions.

Before starting, you can take a look at the project from Plunker.

Initiate the AngularJS project

It’s easy to set up an AngularJS project, you just need embed angular files in the head.

// index.html<html ng-app="angularRouting">
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular-route.min.js"></script><script src="app.js"></script>... // Navigation Menu<ul class="uk-nav uk-nav-default">
<li class="uk-active"> <a href="#">Menu</a></li>
<li><a ng-href="#!">Home</a></li>
<li><a ng-href="#!about">About</a></li>
<li><a ng-href="#!params/1">Params</a></li>
<li><a ng-href="#!auth">You shall not pass!</a></li>
</ul>
// Content will go here
<main ng-view></main>

Your main logic will be in the app.js.

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

Let’s get the routing working

We need to add $routeProvider in order to manage the routing. The code below shows the routing for the home page and the about page. You can test it now in your browser.

The otherwise will redirect all the other routes to the home page. In practical, you will show an 404 template for this one. You can replace template by tempateUrl if you want to separate the HTML template.

// app.jsapp.config(['$routeProvider', 
function($routeProvider){
$routeProvider
.when('/', {
template: '<h1>This is home</h1>'
})
.when('/about', {
template: '<h1>This is about</h1>'
})
.otherwise({
redirectTo: '/'
})
}
]);

Get params from the URL

I created a menu with a parameter. In your application, the parameter will be populated dynamically through {{ id }}. In this example, I will use number 1 as the extra parameter for the params route.

// index.html<ul class="uk-nav uk-nav-default">
<li class="uk-active"> <a href="#">Menu</a></li>
<li><a ng-href="#!">Home</a></li>
<li><a ng-href="#!about">About</a></li>
<li><a ng-href="#!params/1">Params</a></li>
<li><a ng-href="#!auth">You shall not pass!</a></li>
</ul>

Now, we need to config the routing in app.js. I will use ParamsController to get the parameter and show it to the template.

// app.js app.config(['$routeProvider', 
function($routeProvider, $routeParams){
$routeProvider
.when('/', {
template: '<h1>This is home</h1>'
})
.when('/about', {
template: '<h1>This is about</h1>'
})
.when('/params/:id', {
template: '<h1>Param: {{ paramValue }}</h1>',
controller: 'ParamsController'
})

.otherwise({
redirectTo: '/'
})
}
]);
app.controller('ParamsController',
function ParamsController($scope, $routeParams) {
$scope.paramValue = $routeParams.id;
}
);

How to guard your route

So, there are pages that you don’t want to show to the public. User must login in order to view them.

// index.html<ul class="uk-nav uk-nav-default">
<li class="uk-active"> <a href="#">Menu</a></li>
<li><a ng-href="#!">Home</a></li>
<li><a ng-href="#!about">About</a></li>
<li><a ng-href="#!params/1">Params</a></li>
<li><a ng-href="#!auth">You shall not pass!</a></li>
</ul>
{{ message }} //show authentication message
<main ng-view></main>

Then you will add the route and authentication service in app.js. If user doesn’t have the permission to view the page, they will be redirected to the home page.

// app.js // Handle $routeChangeError 
app.run(['$rootScope', '$location',
function($rootScope, $location) {
$rootScope.$on('$routeChangeError', function(event, next, previous, error) {
if(error == 'AUTH_REQUIRED') {
$rootScope.message = 'Sorry, you must log in to access that page';
$location.path('/');
} //AUTH_REQUIRED
}); // $routeChangeError
}
]);
app.config(['$routeProvider',
function($routeProvider, $routeParams){
$routeProvider
.when('/', {
template: '<h1>This is home</h1>'
})
.when('/about', {
template: '<h1>This is about</h1>'
})
.when('/params/:id', {
template: '<h1>Param: {{ paramValue }}</h1>',
controller: 'ParamsController'
})
.when('/auth', {
template: '<h1>Success</h1>',
resolve: {
currentAuth: function(AuthService) {
return AuthService.authenticate();
}
}
})

.otherwise({
redirectTo: '/'
})
}
]);
// Authentication Service
app.factory('AuthService', function($q) {
return {
authenticate: function() {
// Your authenication logic
return $q.reject('AUTH_REQUIRED');
}
}
});

I assume that user doesn’t have the permission to view the page, and it will return an ‘AUTH_REQUIRED’ error.

From now, you know how to handle AngularJS routing with Angular-Route (ngRoute). I will update the UI-Router version shortly.

Hope this helps :)

--

--