Quantcast
Channel: Infragistics Community
Viewing all articles
Browse latest Browse all 2374

Simplifying Routing in AngularJS

$
0
0

Usually AngularJS is used to create a single page application with multiple views. But we can create multiple views in an AngularJS-based single page application by using routing – and in this post we’ll learn how to do that!

What is Routing?

Routing allows us to logically divide the application in the multiple logical views to be loaded asynchronously.  Let’s take, for example, a single page Product application. We can break the various tasks that can be performed on that product into separate logical views as shown below,

·         View to add a product

·         View to delete a product

·         View to edit a product

·         View to display the products.

In AngularJS routing, each view has its own URL. For example, the four views of a single page product application as listed above may have URLs as shown below:

 

When we navigate to /ProductApp.html/#Add URL in the browser, the add view will be loaded asynchronously in the application main view. These views would be loaded asynchronously using routing in the application.

 

Routing Steps in AngularJS

More or less, we do the following tasks to accomplish routing in AngularJS:

·         Inject the route module in the app module

·         Add the $routeProvider in the config of the app module

·         Configure the routes

·         Create a controller for the templates

·         Create a view template as a separate html file (we may also have local views in JavaScript with the type text/ng-template)

·         Create the main view section in the HTML using the ng-view directive

To enable routing in the AngularJS app, we need to take the following steps:

 

Step 1

Add a reference of the AngularJS route library in the main html.

<scriptsrc="../Scripts/angular.js">script>

<scriptsrc="../Scripts/angular-route.js">script>

 

Step 2

Inject the ngRoute module to the main application module.

var MyApp = angular.module('MyApp', ['ngRoute']);

 

Step 3

Configure the routes by providing the following:

1.       URL of the route

2.       View template for the route

3.       Controller associated with the route

We can configure a route as shown below:

MyApp.config(['$routeProvider',

  function ($routeProvider) {

      $routeProvider.

        when('/Add', {

            templateUrl: 'templates/add.html',

            controller: 'AddController'

        }).

        when('/Update', {

            templateUrl: 'templates/update.html',

            controller: 'UpdateController'

        }).

        when('/Delete', {

             templateUrl: 'templates/delete.html',

             controller: 'DeleteController'

        }).

        when('/Show', {

             templateUrl: 'templates/show.html',

             controller: 'ShowController'

         }).

        otherwise({

            redirectTo: '/Show'

        });

  }]);

In the configure route above, whenever we navigate to baseurl/Add:

1.       Add.html template will be loaded in the view

2.       The AddController controller will pass #scope object to the template. Keep in mind that we may work with more than one controller on the view - and it’s also not mandatory to have a controller value configured at the time of route configuration.

 

Step 4

Creating the controllers: In AngularJS, a controller holds data and business logic. Each view will have their own data and the business logic. We can have controllers either inside the controller module or in the main module.

Controllers can be created in the main module as shown below:

 

MyApp.controller('AddController', function ($scope) {

 

    $scope.message = "Add View"

});

MyApp.controller('ÚpdateController', function ($scope) {

 

    $scope.message = "Update View"

});

MyApp.controller('DeleteController', function ($scope) {

 

    $scope.message = "Delete View"

});

MyApp.controller('ShowController', function ($scope) {

 

    $scope.message = "Home View"

});

 

Here we have created controllers with only one message property attached to the $scope object.

 

Step 5

Creating the templates: We have configured the route to keep the templates inside the templates folder of the application, however keep in mind that this is not mandatory. The template can be anywhere inside the application. Templates are the html file.

In this example we have created a templates folder, where we’ve added three html files: add.html, update.html, and delete.html.

add.html will look like this:

<divclass="jumbotron text-center"ng-controller="AddController">

    <h1>Add Viewh1>

    <p>{{message}}p>

div>

 

Exactly like the add.html, we can create other templates for update and delete.

 

Step 6

Creating the main view: In the main view, let’s go ahead and create a menu with bootstrap and add a div with directive ng-view.

 

        <navrole="navigation"class="navbar navbar-default">

            <divclass="navbar-header">              

                <ulclass="nav navbar-nav">

                    <liclass="active"><ahref="#Show">Homea>li>

                    <li><ahref="#Add">Adda>li>

                    <li><ahref="#Update">Updatea>li>

                    <li><ahref="#Delete">Deletea>li>

                ul>

            div>

        nav>

 

         <divng-view>div>

           

        div>

 

This view will be loaded in the div, attributed with the ng-view directive. Here we have configured the URL of the menu items to the routes name configured.  Also make sure that the ng-app directive value is set to the MyApp and references to the AngularJS library and AngularJS Route libraries are added to the html.  So the Index.html header will look like this:

 

<htmlng-app="MyApp">

<head>

    <title>Professional Tutortitle>

    <linkhref="../Content/bootstrap.css"rel="stylesheet"/>

    <scriptsrc="../Scripts/angular.js">script>

    <scriptsrc="../Scripts/angular-route.js">script>

    <scriptsrc="home.js">script>

head>

<body>

 

Running the application

On running the application, we can navigate to different views by appending the route name in the base URL. Now we have a complete single-page application in which different views are loaded asynchronously.

 

 

Passing Data to the View

We may have a requirement to pass data to the view. Let’s say we are working on a detailed view of a particular product. In that case, we need to pass the id of the product to display the details of that particular product. To pass the id, we need to configure the route as shown below:

 

when('/Show/:id', {

            templateUrl: 'templates/show.html',

             controller: 'ShowController'

         }).

 

And then in the ShowController we can read the id as shown below:

 

MyApp.controller('ShowController', function ($scope,$routeParams) {

 

    $scope.ProductId = $routeParams.id;

});

 

We can pass the id while navigating to the show view as shown in the listing below:

 

<liclass="active"><ahref="#Show/45">Showa>li>

 

Navigating on the button click

We may have another requirement to navigate to a particular view then a button is clicked. The example below shows how that can be done. In short, we need to call the function changeview on the ng-click of the button to navigate to the Update view:

 

MyApp.controller('SearchController', function ($scope, $http, $location) {

 

   

    $scope.changeview = function () {

        $location.path('/Update');

    }

 

});

 

Conclusion

In this post we covered everything you need to know to work with routing, different views, and single page applications in AngularJS. I hope this post is useful, thanks for reading!

Looking for an advanced set of HTML5 & JavaScript UI controls and components? Download IgniteUI now and see what it can do for you!



Viewing all articles
Browse latest Browse all 2374

Trending Articles