This example shows setting up a small application with 3 routes, each with it's own view and controller, using the controllerAs syntax.
We configure our router at the angular .config function
$routeProvider into .config.when method with a route definition object..when method with an object specifying our template or templateUrl, controller and controllerAsapp.js
angular.module('myApp', ['ngRoute'])
.controller('controllerOne', function() {
this.message = 'Hello world from Controller One!';
})
.controller('controllerTwo', function() {
this.message = 'Hello world from Controller Two!';
})
.controller('controllerThree', function() {
this.message = 'Hello world from Controller Three!';
})
.config(function($routeProvider) {
$routeProvider
.when('/one', {
templateUrl: 'view-one.html',
controller: 'controllerOne',
controllerAs: 'ctrlOne'
})
.when('/two', {
templateUrl: 'view-two.html',
controller: 'controllerTwo',
controllerAs: 'ctrlTwo'
})
.when('/three', {
templateUrl: 'view-three.html',
controller: 'controllerThree',
controllerAs: 'ctrlThree'
})
// redirect to here if no other routes match
.otherwise({
redirectTo: '/one'
});
});
Then in our HTML we define our navigation using <a> elements with href, for a route name of helloRoute we will route as <a href="/?originalUrl=https%3A%2F%2Friptutorial.com%2F%26quot%3B%23%2FhelloRoute%26quot%3B%26gt%3BMy%2520route%26lt%3B%2Fa%26gt%3B%253C%2Fcode">
We also provide our view with a container and the directive ng-view to inject our routes.
index.html
<div ng-app="myApp">
<nav>
<!-- links to switch routes -->
<a href="/?originalUrl=https%3A%2F%2Friptutorial.com%2F%26quot%3B%23%2Fone%26quot%3B%26gt%3BView%2520One%26lt%3B%2Fa%26gt%3B%2520%2520%2520%2520%26lt%3Ba%2520href%3D%26quot%3B%23%2Ftwo%26quot%3B%26gt%3BView%2520Two%26lt%3B%2Fa%26gt%3B%2520%2520%2520%2520%26lt%3Ba%2520href%3D%26quot%3B%23%2Fthree%26quot%3B%26gt%3BView%2520Three%26lt%3B%2Fa%26gt%3B%2520%2520%26lt%3B%2Fnav%26gt%3B%2520%2520%26lt%3B!--%2520views%2520will%2520be%2520injected%2520here%2520--%26gt%3B%2520%2520%26lt%3Bdiv%2520ng-view%26gt%3B%26lt%3B%2Fdiv%26gt%3B%2520%2520%26lt%3B!--%2520templates%2520can%2520live%2520in%2520normal%2520html%2520files%2520--%26gt%3B%2520%2520%26lt%3Bscript%2520type%3D%26quot%3Btext%2Fng-template%26quot%3B%2520id%3D%26quot%3Bview-one.html%26quot%3B%26gt%3B%2520%2520%2520%2520%26lt%3Bh1%26gt%3B%7B%7BctrlOne.message%7D%7D%26lt%3B%2Fh1%26gt%3B%2520%2520%26lt%3B%2Fscript%26gt%3B%2520%2520%26lt%3Bscript%2520type%3D%26quot%3Btext%2Fng-template%26quot%3B%2520id%3D%26quot%3Bview-two.html%26quot%3B%26gt%3B%2520%2520%2520%2520%26lt%3Bh1%26gt%3B%7B%7BctrlTwo.message%7D%7D%26lt%3B%2Fh1%26gt%3B%2520%2520%26lt%3B%2Fscript%26gt%3B%2520%2520%26lt%3Bscript%2520type%3D%26quot%3Btext%2Fng-template%26quot%3B%2520id%3D%26quot%3Bview-three.html%26quot%3B%26gt%3B%2520%2520%2520%2520%26lt%3Bh1%26gt%3B%7B%7BctrlThree.message%7D%7D%26lt%3B%2Fh1%26gt%3B%2520%2520%26lt%3B%2Fscript%26gt%3B%26lt%3B%2Fdiv%26gt%3B%253C%2Fcode">