/*!
** ngRouter App
** Licensed under the Apache License v2.0
** http://www.apache.org/licenses/LICENSE-2.0
** Built by Jay Kanakiya ( @techiejayk )
**/
"use strict";
var App = angular.module("example",["ngRoute"]);
App.controller("ExmpCtrl",function ($scope,$route) {
$scope.message = "Takes it from Parent";
$scope.debug = $route;
});
App.controller("ChildCtrl1",function ($scope) {
$scope.message = "Link 1 has been Visited";
});
App.controller("ChildCtrl2",function ($scope) {
$scope.message = "Link 2 has been Visited";
});
App.config(function ($routeProvider,$locationProvider) {
$routeProvider
.when("/link1",{
templateUrl : "hello.html" , controller : "ChildCtrl1"
})
.when("/link2",{
templateUrl : "hello2.html" , controller : "ChildCtrl2"
})
.otherwise({
templateUrl : "hello3.html"
//redirectTo: '/' //Used to redirect to index
});
$locationProvider.html5Mode(true);
});
<!doctype html>
<html ng-app="example">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-animate.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular-route.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<script type="text/javascript">
//this is here to make plunkr work with AngularJS routing
angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
</script>
</head>
<body>
<div class="row" ng-controller="ExmpCtrl">
<p><a href="link1">Link1</a></p>
<p><a href="link2">Link2</a></p>
<p><a href="#">Back</a></p>
</div>
<div ng-view></div>
</div>
</body>
</html>
<h1>Hello World from Link1</h1>
{{message}}
Since Angular version 1.2 , you need to angular-route is in a different module and needs to be included seperately .
$routeProvider is angular module where we define the templateUrl and the controller.We need to define the routes inside App.config and give the template Url.The template can be defined <a href="http://docs.angularjs.org/api/ng.directive:script" target="_blank">inlined</a> inside script tags as follows
<script type= text/ng-template>Your html Template</script>
or can be external html files.
ng-view is the directive that directly complements $route.
<blockquote>ngView is a directive that complements the $route service by including the rendered template of the current route into the main layout (index.html) file. Every time the current route changes, the included view changes with it according to the configuration of the $route service.</blockquote>
This example shows how changing the URL hash causes the $route to match a route against the URL, and the ngView pulls in the partial.
Click on the hello link and you will see the url change and the template gets loaded.
<h1>Hello World from Link2</h1>
{{message}}