Part 23 AngularJS routing tutorial
In general, as the application becomes complex you will have more than one view in the application. Let's say you are building a single page application for a training institute and you have the following views
- Home
- Courses
- Students
We can take advantage of the Angular routing feature, to have a single layout page, and then inject and swap out different views depending on the URL the end user has requested.
So in our application we will have the following views
index.html is the layout view
home.html, courses.html & students.html will be injected into the layout view(index.html) depending on the URL the end user has requested
For example, if the user has requested http://localhost:51983/home, then home.html will be injected into the layout view (index.html). Similarly if the user has requestedhttp://localhost:51983/courses, then courses.html will be injected into the layout view (index.html).
Preparing the angular application application to use routing : The AngularJS Route module is present in a separate JavaScript file. You can either download it from AngularJs.org and use it in the application or you can use the CDN link.
Part 24 Angular layout template
The layout page for our example should be as shown below.
Here are the steps
Step 1 : Copy and paste the following HTML in the body section of the page.
<table style="font-family: Arial"> <tr> <td colspan="2" class="header"> <h1> WebSite Header </h1> </td> </tr> <tr> <td class="leftMenu"> <a href="#/home">Home</a> <a href="#/courses">Courses</a> <a href="#/students">Students</a> </td> <td class="mainContent"> <ng-view></ng-view> </td> </tr> <tr> <td colspan="2" class="footer"> <b>Website Footer</b> </td> </tr> </table>
Please note :
1. The partial templates (home.html, courses.html & students.html) will be injected into the location where we have ng-view directive.
2. For linking to partial templates we are using # symbol in the href attribute. This tells the browser not to navigate away from index.html. In a later video we will discuss how to get rid of the # symbol.
At this point, if you navigate to index.html, the page looks as shown below. This is because we do not have the styles applied yet.
Step 2 : Add a stylesheet to your project. Name it styles.css. Copy and paste the following.
.header { width: 800px; height: 80px; text-align: center; } .footer { text-align: center; } .leftMenu { height: 500px; width: 150px; } .mainContent { height: 500px; width: 650px; } a{ display:block; padding:5px }
Step 3 : Finally add a reference to styles.css in index.html page. At this point the HTML in the layout page (index.html) should be as shown below.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" ng-app="Demo"> <head> <title></title> <script src="Scripts/angular.min.js"></script> <script src="Scripts/angular-route.min.js"></script> <link href="Styles.css" rel="stylesheet" /> </head> <body> <table style="font-family: Arial"> <tr> <td colspan="2" class="header"> <h1> WebSite Header </h1> </td> </tr> <tr> <td class="leftMenu"> <a href="#/home">Home</a> <a href="#/courses">Courses</a> <a href="#/students">Students</a> </td> <td class="mainContent"> <ng-view></ng-view> </td> </tr> <tr> <td colspan="2" class="footer"> <b>Website Footer</b> </td> </tr> </table> </body> </html>
Part 25 Angularjs partial templates
One important thing to keep in mind is that, since we have all the surrounding HTML (i.e html, head, body etc) in the layout view (index.html), there is no need to include that same surrounding HTML again in the partial templates.
All our partial templates are going to be in Templates folder. So first add Templates folder to the project's root folder.
home.html : Right click on the Templates folder and add a new HTML file. Name it home.html. Copy and paste the following. The homeController will set the message property on the $scope object. We will discuss creating the homeController in a later video.
<h1>{{message}}</h1> <div> PRAGIM Established in 2000 by 3 S/W engineers offers very cost effective training. PRAGIM Speciality in training arena unlike other training institutions </div> <ul> <li>Training delivered by real time software experts having more than 10 years of experience.</li> <li>Realtime projects discussion relating to the possible interview questions.</li> <li>Trainees can attend training and use lab untill you get a job.</li> <li>Resume preperation and mock up interviews.</li> <li>100% placement assistance.</li> <li>Lab facility.</li> </ul>
courses.html : The coursesController will set the courses property on the $scope object. We will discuss creating the coursesController in a later video.
<h1>Courses we offer</h1> <ul> <li ng-repeat="course in courses"> {{course}} </li> </ul>
students.html : The students data is going to come from a database table. So here are the steps
Step 1 : Create the database table (tblStudents) and populate it with test data.
Create table tblStudents ( Id int primary key identity, Name nvarchar(50), Gender nvarchar(10), City nvarchar(20) ) Go Insert into tblStudents values ('Mark', 'Male', 'London') Insert into tblStudents values ('John', 'Male', 'Chennai') Insert into tblStudents values ('Sara', 'Female', 'Sydney') Insert into tblStudents values ('Tom', 'Male', 'New York') Insert into tblStudents values ('Pam', 'Male', 'Los Angeles') Insert into tblStudents values ('Catherine', 'Female', 'Chicago') Insert into tblStudents values ('Mary', 'Female', 'Houston') Insert into tblStudents values ('Mike', 'Male', 'Phoenix') Insert into tblStudents values ('Rosie', 'Female', 'Manchester') Insert into tblStudents values ('Sasha', 'Female', 'Hyderabad') Go
Step 2 : Include the following configuration in web.config file. Notice we have a connection string to the database. We also have enabled HttpGet protocol for ASP.NET web services.
<?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="DBCS" connectionString="server=(local);database=SampleDB; integrated security=true" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <webServices> <protocols> <add name="HttpGet" /> </protocols> </webServices> </system.web> </configuration>
Step 3 : Add a class file to the project. Name it Student.cs. Copy and paste the following code.
namespace Demo { public class Student { public int id { get; set; } public string name { get; set; } public string gender { get; set; } public string city { get; set; } } }
Step 4 : Add an ASMX web service to the project. Name it StudentService.asmx. Copy and paste the following code.
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Web.Script.Serialization; using System.Web.Services; namespace Demo { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class StudentService : System.Web.Services.WebService { [WebMethod] public void GetAllStudents() { List<Student> listStudents = new List<Student>(); string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; using (SqlConnection con = new SqlConnection(cs)) { SqlCommand cmd = new SqlCommand("Select * from tblStudents", con); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Student student = new Student(); student.id = Convert.ToInt32(rdr["Id"]); student.name = rdr["Name"].ToString(); student.gender = rdr["Gender"].ToString(); student.city = rdr["City"].ToString(); listStudents.Add(student); } } JavaScriptSerializer js = new JavaScriptSerializer(); Context.Response.Write(js.Serialize(listStudents)); } } }
Step 5 : Right click on the Templates folder and add a new HTML file. Name it students.html. Copy and paste the following. The studentsController will set the students property on the $scope object. We will discuss creating the studentsController in a later video.
<h1>List of Students</h1> <ul> <li ng-repeat="student in students"> {{student.name}} </li> </ul>
Right click on the Scripts folder and add a new JavaScript file. Name it script.js. Copy and paste the following code.
/// <reference path="angular.min.js" /> var app = angular .module("Demo", ["ngRoute"]) .config(function ($routeProvider) { $routeProvider .when("/home", { templateUrl: "Templates/home.html", controller: "homeController" }) .when("/courses", { templateUrl: "Templates/courses.html", controller: "coursesController" }) .when("/students", { templateUrl: "Templates/students.html", controller: "studentsController" }) }) .controller("homeController", function ($scope) { $scope.message = "Home Page"; }) .controller("coursesController", function ($scope) { $scope.courses = ["C#", "VB.NET", "ASP.NET", "SQL Server"]; }) .controller("studentsController", function ($scope, $http) { $http.get("StudentService.asmx/GetAllStudents") .then(function (response) { $scope.students = response.data; }) })
2 Changes to index.html
1. Add a reference to the script.js file in the layout template i.e index.html.
2. Set ng-app="Demo" on the root html element
At this point, depending on the URL, the respective partial template will be injected into the layout template in the location where we have ng-view directive. For example if you have index.html#/home, then home.html is injected into index.html. Similarly if you are on index.html#/courses, then course.html is injected into index.html.