AngularJS Routing

Ratings:
(4)
Views:0
Banner-Img
  • Share this blog:

AngularJS routes enable us to create different URLs for different content in our application. A route is specified in the URL after the # sign. Thus, all the following URLs point to the same AngularJS application, but each points to a different route:

http://tekslate.com/index.html# view1
http://tekslate.com/index.html# view2
http://tekslate.com/index.html# view3
http://tekslate.com/index.html# view4

When the browser loads these links, the same AngularJS application will be loaded (located athttp://tekslate.com/index.html), but AngularJS will look at the route (the part of the URL after the #) and decide what HTML template to show.

Working AngularJS route example :

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
</head>

<body ng-app="sampleApp">

<a href="#/route1">Route 1</a><br/>
<a href="#/route2">Route 2</a><br/>


<div ng-view></div>

<script>
    var module = angular.module("sampleApp", ['ngRoute']);

    module.config(['$routeProvider',
        function($routeProvider) {
            $routeProvider.
                when('/route1', {
                    templateUrl: 'angular-route-template-1.jsp',
                    controller: 'RouteController'
                }).
                when('/route2', {
                    templateUrl: 'angular-route-template-2.jsp',
                    controller: 'RouteController'
                }).
                otherwise({
                    redirectTo: '/'
                });
        }]);

    module.controller("RouteController", function($scope) {

    })
</script>

AngularJS Route Module

The AngularJS Route module is contained in its own JavaScript file. To use it we must include in our AngularJS application.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>

Declaring a Dependency on the AngularJS Route Module

AngularJS module (called sampleApp) declares a dependency on the AngularJS route module:

var module = angular.module("sampleApp", ['ngRoute']); The application's module needs to declare this dependency in order to use the ngRoute module.

ng-view Directive

the div with the ngView directive (can also be written ng-view) the HTML template specific to the given route will be displayed.

<div ng-view></div>

Routes link When one of these links is clicked, the URL in the browser window changes, and the div with the ngViewdirective will show the HTML template matching the route path.

<a href="#/route1">Route 1</a><br/> <a href="#/route2">Route 2</a><br/>

Aspired to become an AngularJS Developer? Explore the post to discover the know-hows on
 AngularJS Training in Hyderabad.

AngularJs Route Parameters

There are a number of ways optional parameters can be declared when using UI Router.

Query Parameters

Query parameters are mapped to UI Router's $stateParams object, you need to declare them in your state configuration's URL template:

state('new-qs',

{ url: '/new?portfolioId',

templateUrl: 'new.html',

controller: function($scope, $stateParams) {

$scope.portfolioId = $stateParams.portfolioId;

}

})

create a link to this state using the ui-sref attribute:

<a ui-sref="new-qs({ portfolioId: 1 })">New (query string)</a>

This will navigate to /new?portfolioId=1.

Multiple optional parameters, separate them with an &:

state('new-qs', {

url: '/new?portfolioId&param1&param2',

templateUrl: 'new.html',

controller: function($scope, $stateParams) {

$scope.portfolioId = $stateParams.portfolioId;

$scope.param1 = $stateParams.param1;

$scope.param2 = $stateParams.param2;

}

})

Optional Route Parameters

Route parameters in UI Router are optional by default. This means that in the example below both /new/2 and /new/ would work, but not /new.he ? suffix you often see on route parameters simply tells UI Router where the query portion of the URL template should start e.g. /new/:portfolioId?.

Updating the ui-sref attribute to new-rp({ portfolioId: 2 }) will produce the link/new/2.

For multiple optional route parameters e.g. /posts/tagged/:tag/page/:page it looks like the only solution right now is to declare multiple routes i.e. /posts/tagged/:tag and/posts/tagged/:tag/page/:page.

 Non-URL route parameters

How to pass parameters that do not appear in the URL. This is particularly useful for abstract states.

state('new-nonurl', {

url: '/new',

params: {

portfolioId: null,

},

templateUrl: 'new.html',

controller: function($scope, $stateParams) {

$scope.portfolioId = $stateParams.portfolioId;

}

})

Now ui-sref="new-nonurl({ portfolioId: 3 })" will generate the link \new but still pass the portfolioId parameter in $stateParams.

For an Indepth knowledge on AngularJS, click on below

You liked the article?

Like : 0

Vote for difficulty

Current difficulty (Avg): Medium

About Author
Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.


Stay Updated


Get stories of change makers and innovators from the startup ecosystem in your inbox