Angularjs Examples

AJS Examples


AngularJS Routing

AngularJS has special type of service called route provider which enable you to create different URLs for different content in your application. Routing divide your application into logical views and as on requirement it loads view into the single page. This concept makes your application code more manageable.

AngularJS provides you built in provider called $routeProvider. The $routeProvider is what creates the $route service. In order to configure $routeProvider, you need to use module's config() function, which takes the $routeProvider as parameter.

The $routeProvider is configured with the help of when() and otherwise() functions. The when() function takes a route path and a JavaScript object as parameters. The route path is matched against the part of the URL after the # when the application is loaded.

The JavaScript object contains two properties named templateUrl and controller.

The templateUrl property tells which HTML template AngularJS should load and display inside the div with the ngView directive. The controller property tells which of your controller functions that should be used with the HTML template.

Syntax

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/path1', {
                    templateUrl: 'angular-path1.php',
                    controller: 'PathController'
                }).
                when('/path2', {
                    templateUrl: 'angular-path2.php',
                    controller: 'PathController'
                }).
                otherwise({
                    redirectTo: '/defaultPath'
                });
        }]);

AngularJS Routing Example

<html>
<head>
<title>My first AngularJS Routing code</title>
<Script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</Script>
<Script>
sampleApp.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/path1', {
                    templateUrl: 'angular-path1.html',
                    controller: 'PathControllerOne'
                }).
                when('/path2', {
                    templateUrl: 'angular-path2.html',
                    controller: 'PathControllerTwo'
                }).
                otherwise({
                    redirectTo: '/angular-path1.html'
                });
        }]);

sampleApp.controller('PathControllerOne', function($scope) {
	$scope.message = 'This is AngularJS path one example';
});
sampleApp.controller('PathControllerTwo', function($scope) {
	$scope.message = 'This is AngularJS path two example';
});
</Script>
</head>
<body>
<div ng-app="sampleApp">
<div class="row">
	<div>
	   <ul>
			<li><a href="#path1"> Show Path One </a></li></br>
			<li><a href="#path2"> Show Path Two </a></li>
		</ul>
	</div>
	<div">
		<div ng-view></div>
	</div>
</div>
</div>
</body>
</html>
See Live Example