AngularJS route

AngularJS route example:

index.html:

<!doctype html>
<html ng-app="app">
<head>
	<meta charset="utf-8">
	<title>AngularJS dev</title>
 
	<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
	<link href="css/style.css" rel="stylesheet">
 
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.2/angular.js"></script>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.2/angular-route.js"></script>
 
	<script src="js/app.js"></script>
 
</head>
 
<body>
 
<section class="container">
 
	<a href="#/list">list of countries</a> |
	<a href="#/add">add new country</a>
 
	<div ng-view></div>
 
</section>
 
</body>
</html>

app.js:

var app = angular.module('app', ['ngRoute']);
 
app.config(['$routeProvider', function($routeProvider) {
	$routeProvider.
		when('/list', {
			templateUrl: 'js/templates/list.html',
			controller: 'appController'
		}).
		when('/add', {
			templateUrl: 'js/templates/add.html',
			controller: 'appController'
		}).
		otherwise({
			redirectTo: '/list'
		});
}]);
 
app.controller('appController', function($scope){
 
	$scope.countriesList = [
		{name: 'Germany', capital: 'Berlin', population: '81,305,856'},
		{name: 'France', capital: 'Paris', population: '65,630,692'},
		{name: 'Italy', capital: 'Rome', population: '61,261,254'},
		{name: 'Spain', capital: 'Madrid', population: '47,042,984'},
		{name: 'United Kingdom', capital: 'London', population: '63,047,162'}
	];
 
	$scope.addCountry = function(){
		$scope.countriesList.push( { name: $scope.newCountry.name, capital: $scope.newCountry.capital } );
	};
 
});

templates/list.html:

<h3>List of countries</h3>
 
<ul>
	<li ng-repeat="country in countriesList">
		<a href="#">{{country.name}}</a>
	</li>
</ul>

templates/add.html:

<h3>List of countries</h3>
 
<ul>
	<li ng-repeat="country in countriesList">
		<a href="#">{{country.name}}</a>
	</li>
</ul>
 
 
<h3>Add new country</h3>
 
<p>Name: <input type="text" ng-model="newCountry.name" /> </p>
 
<p>Capital: <input type="text" ng-model="newCountry.capital" /></p>
 
<p><button ng-click="addCountry()">Add new country to the list</button></p>

Leave a Reply

Your email address will not be published. Required fields are marked *