AngularJS Routing Using WebService

Overview

In this article, we will see AngularJS routing with an example and we will see how to develop an Single Page Application(SPA). In this we will cover a simple small demo consisting of pages like ,

  • Index Page(Our Home Page)
  • Templates Folder in templates folder we will have pages like home,courses and students respectively.

Note 1 - Views will injected into layout view depending upon the URL requested.
Note 2 - The Angular JS Route module is present in seprate javascript file.

In this article, we will see-

  • AngularJS Route Configuration.
  • Remove # from URL’s in AngularJS.
  • Default Route in Angular JS.
  • AngularJS Intellisense.

demo

For more articles on Angular JS, refer here-

Introduction

Before starting AngularJS routing example, we need to download a separate file of AngularJS routing from Angular JS Website. Thus, from the official website, lets download the file. Let's browse.

AngularJS
Click AngularJS1 and you will get the prompt, given below- 

prompt

When you click Download button, it contains a core Angular script, which does not contain AngularJS routing module. Thus, click browse additional modules.

prompt

On the next page, you will see Javascript file, which contains routing modules.

 javascript file

You can see, we have two versions of Angular JS and we will be using minified version of AngularJS. Thus, click it  and will open a separate Window, copy it and save it in Notepad as angular-route.min.js.

angular-route.min.js


Your Application will look like-

reference

Let's add a page in your Application as index.html and this will be our home page.

Page

Now, we will reference our core Angular script file and route file in out HTML page as, given below-
  1. <script src="scripts/angular.min.js"></script>  
  2. <script src="scripts/angular-route.min.js"></script>  
You can also use CDN link for AngularJS routing module. What is CDN link here ?

CDN link

Look at this CDN link here for Angular JS for which, look at CDN link carefully. It doesn’t have route here. We will just add the route name here and just copy that CDN link and the URL, given below-

https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.min.js


Thus, this will be your CDN link for AngularJS routing module .

Lets get back to our Page Index Page. We will first design a Header and Footer for our Page and apply some styles to it. Thus, we will design our stylesheet here. Just add a simple header and footer in those styles as, given below-
  1. .header {  
  2. width:800px;  
  3. height:80px;  
  4. text-align:center;   
  5. background-color:#BDBDBD;  
  6. }  
  7.   
  8. .footer {  
  9. text-align:center;   
  10. background-color:#BDBDBD;  
  11. }  
  12.   
  13. .leftMenu {  
  14. height:500px;  
  15. background-color:#D8D8D8;  
  16. width:150px;  
  17. }  
  18.   
  19. .mainContent {  
  20.   
  21. height:500px;  
  22. background-color:#E6E6E6;  
  23. width:650px;  
  24. }  
  25.   
  26. a {  
  27. display:block;  
  28. padding:5px;  
  29. }  
Save these stylesheet as Styles.css and reference it in your HTML page.
  1. <link href="Styles.css" rel="stylesheet" />  
In our HTML page, we will make a header, footer and design a layout for that as, given below-
  1. <table>  
  2.     <tr>  
  3.         <td colspan="2" class="header">  
  4.             <h1> Demo Application</h1>  
  5.         </td>  
  6.     </tr>  
  7.     <tr>  
  8.         <td class="leftMenu"> Links </td>  
  9.         <td class="mainContent"> home/Courses/Students </td>  
  10.     </tr>  
  11.     <tr>  
  12.         <td colspan="2" class="footer">  
  13.             <h1> Demo Application </h1>  
  14.         </td>  
  15.     </tr>  
  16. </table>  
Paste this code in your body tag. Now, just run the Application and you will see-

application
As you can see, we got the desired result, we had got header and footer of our Demo Application and Links, which we referenced .

Now, we will add the links as home, courses and students. In those, we will add the links with the help of an anchor tag and also before it, we will write #/ to denote the Browser, which we don’t want to navigate from our home page i.e from index.html. 

Hence, just add these three lines as-
  1. <a href="#/home">Home</a>  
  2. <a href="#/courses">Courses</a>  
  3. <a href="#/students">Students</a>  
Now, just run the Application and lets check the output-

output
You can see, we got the links. Now, when you hover on those links at the bottom, you will see the URL. We actually don’t want that. We will remove those, using the routing templates by using the partial templates.

Now, we will be creating the partial templates for our courses and students views. We will be creating those in partial templates and we will add a new folder to our solution. We will name it as templates.

When you create a Template folder, create a new HTML Page in it and name it as home.html as, given below-

Template

Now, in home.html, remove all the the tags. Here, I had copied SQL Server contents from Wikipedia, just to show you the demo.

Now, we will display at the top as Home Page, which will be from $scope object and and will display a message.

Thus, just add these lines of code in our home.html page as-
  1. <h1>{{message}}</h1>  
  2. <div> In 1988, Microsoft joined Ashton-Tate and Sybase to create a variant of Sybase SQL Server for IBM OS/2 (then developed jointly with Microsoft), which was released the following year.[4] This was the first version of Microsoft SQL Server, and served as Microsoft's entry to the enterprise-level database market, competing against Oracle, IBM, and later, Sybase. SQL Server 4.2 was shipped in 1992, bundled with OS/2 version 1.3, followed by version 4.21 for Windows NT, released alongside Windows NT 3.1. SQL Server 6.0 was the first version designed for NT, and did not include any direction from Sybase.  
  3.     <ul>  
  4.         <li>The protocol layer implements the external interface to SQL Server. All operations that can be invoked on SQL Server are communicated to it via a Microsoft-defined format, called Tabular Data Stream (TDS). TDS is an application layer protocol, used to transfer data between a database server and a client. Initially designed and developed by Sybase Inc.</li>  
  5.     </ul>  
  6. </div>  
Now, let's create courses page in Templates folder only.

Now, in courses page, whatever courses are there, will come from courses controller, so we will be using here ng-repeat directive to bind those courses. 

Thus, write this code in courses.html page, given below-
  1. <h1>Courses</h1>  
  2. <div>  
  3.     <ul>  
  4.         <li ng-repeat="course in courses"> {{course}} </li>  
  5.     </ul>  
  6. </div>  
Now, let's create a page for students. In this, we will display the list of students for that the students list, which will generate from our database. For it, let's create a table first, insert some data and then add that connection string in our web.config file.

Code to create a table and insert script is given below-

Create Table script

  1. CREATE TABLE STUDENTS  
  2. (id int primary key identity,  
  3. name nvarchar(max),  
  4. city nvarchar(max),  
  5. gender nvarchar(max))  
Insert some data, as given below-
  1. insert into STUDENTS values('Akshay','Mumbai','Male')  
  2. insert into STUDENTS values('Hari','Mumbai','Male')  
  3. insert into STUDENTS values('Raghvan','Pune','Male')  
  4. insert into STUDENTS values('Milind','nashik','Male')  
  5. insert into STUDENTS values('Gopal','Delhi','Male')  
Now, let's add connection string in our web.config file as-
  1. <configuration>  
  2.     <connectionStrings>  
  3.         <add name="Test" connectionString="Data Source=DESKTOP-QOMPPF7;Initial Catalog=TEST;Persist Security Info=True;User ID=sa;Password=p@ssw0rd" providerName="System.Data.SqlClient" /> </connectionStrings>  
  4.     <system.web>  
  5.         <compilation debug="true" targetFramework="4.0" />  
  6.         <webServices>  
  7.             <protocols>  
  8.                 <add name="HttpGet" /> </protocols>  
  9.         </webServices>  
  10.     </system.web>  
  11. </configuration>  
We had written HttpGet, which tells our Webservice to retrieve the records from our database.

Now, next step is to create a student class with its corresponding values.

values
Thus, let's create a class called students and add the properties to it.
  1. public int id { get; set; }  
  2. public string name { get; set; }  
  3. public string city { get; set; }  
  4. public string gender { get; set; }  
Now, let's quickly create a Webservice. In it, we will write some code to retrieve the data from our database. Now, in it, we will write some code as, given below-
  1. public void GetAllStudents()  
  2. {  
  3.         List < Student > listStudents = new List < Student > ();  
  4.         string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  5.         using(SqlConnection con = new SqlConnection(cs)) {  
  6.             SqlCommand cmd = new SqlCommand("select * from students", con);  
  7.             con.Open();  
  8.             SqlDataReader sdr = cmd.ExecuteReader();  
  9.             while (sdr.Read()) {  
  10.                 Student student = new Student();  
  11.                 student.id = Convert.ToInt32(sdr["id"]);  
  12.                 student.name = sdr["Name"].ToString();  
  13.                 student.gender = sdr["gender"].ToString();  
  14.                 student.city = sdr["city"].ToString();  
  15.                 listStudents.Add(student);  
  16.             }  
  17.         }  
To get JSON output, we will write a namespace as, given below-
  1. using System.Web.Script.Serialization;  
Also, some lines of codes to retrieve the output are as follows-
  1. JavaScriptSerializer js = new JavaScriptSerializer();  
  2. Context.Response.Write(js.Serialize(listStudents));  
Hence, final Webservice code is given below-
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Data;  
  7. using System.Data.SqlClient;  
  8. using System.Configuration;  
  9. using System.Web.Script.Serialization;  
  10. namespace WebApplication1 {  
  11.     /// <summary>  
  12.     /// Summary description for StudentServiceasmx  
  13.     /// </summary>  
  14.     [WebService(Namespace = "http://tempuri.org/")]  
  15.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  16.     [System.ComponentModel.ToolboxItem(false)]  
  17.     // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  18.     [System.Web.Script.Services.ScriptService]  
  19.     public class StudentServiceasmx: System.Web.Services.WebService {  
  20.         [WebMethod]  
  21.         public void GetAllStudents() {  
  22.             List < Student > listStudents = new List < Student > ();  
  23.             string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  24.             using(SqlConnection con = new SqlConnection(cs)) {  
  25.                 SqlCommand cmd = new SqlCommand("select * from students", con);  
  26.                 con.Open();  
  27.                 SqlDataReader sdr = cmd.ExecuteReader();  
  28.                 while (sdr.Read()) {  
  29.                     Student student = new Student();  
  30.                     student.id = Convert.ToInt32(sdr["id"]);  
  31.                     student.name = sdr["Name"].ToString();  
  32.                     student.gender = sdr["gender"].ToString();  
  33.                     student.city = sdr["city"].ToString();  
  34.                     listStudents.Add(student);  
  35.                 }  
  36.             }  
  37.             JavaScriptSerializer js = new JavaScriptSerializer();  
  38.             Context.Response.Write(js.Serialize(listStudents));  
  39.         }  
  40.     }  
  41. }  
Now, let's quickly check our Service. 

service

Let's invoke the Service-

service

We got the desired output. Now, let's create a page called Students.html in our Template folder and we will bind it. 

Get rid of the code now. Here, in our student controller, we included h1 tag to display the list of students and we will use ng-repeat directive to loop in those records as, given below-
  1. <h1>List Of Students </h1>  
  2. <ul>  
  3.     <li ng-repeat="student in students"> {{student.name}} </li>  
  4. </ul>  
Now, we will be looking at the controllers for our demo Application as Home, Courses and Students respectively. Now, we will add a Javascript file and name it as script.js.

In this file, we will name module name as DemoApp.
  1. var app = angular.module("Demo", ["ngRoute"])  
You can see, we had added a dependency as ngRoute. Now, we will add a function as $routeprovider. We will navigate our pages, which are residing under Templates folder and our controller name for our respective pages as well.
  1. .config(function ($routeProvider) {  
  2. $routeProvider  
  3. .when("/home", {  
  4. templateUrl: "Templates/home.html",  
  5. controller:"homeController"  
  6. })  
Similarly, add for rest of the courses and students, given below-
  1. .when("/courses", {  
  2. templateUrl: "Templates/courses.html",  
  3. controller: "coursesController"  
  4. })  
  5.   
  6. .when("/students", {  
  7. templateUrl: "Templates/students.html",  
  8. controller: "studentsController"  
  9. })  
  10.   
  11. })  
Now, we will add controller for the three partial templates and we will be attaching those to our $scope object, as we had written in our respective HTML pages, given below-
  1. .controller("homeController"function ($scope) {  
  2. $scope.message = "Home Page";  
  3. })  
  4.   
  5. .controller("coursesController"function ($scope) {  
  6. $scope.courses = ["c#""SQL""Oracle"];  
  7. })  
  8.   
  9. .controller("studentsController"function ($scope,$http) {  
  10. $http.get("StudentService.asmx/GetAllStudents")  
  11. .then(function(response)  
  12. {  
  13.   
  14. $scope.students = response.data;   
  15.   
  16. })  
Thus, our final code is given below-
  1. /// <reference path="angular.min.js" />  
  2. var app = angular.module("Demo", ["ngRoute"]).config(function($routeProvider) {  
  3.     $routeProvider.when("/home", {  
  4.         templateUrl: "Templates/home.html",  
  5.         controller: "homeController"  
  6.     }).when("/courses", {  
  7.         templateUrl: "Templates/courses.html",  
  8.         controller: "coursesController"  
  9.     }).when("/students", {  
  10.         templateUrl: "Templates/students.html",  
  11.         controller: "studentsController"  
  12.     })  
  13. }).controller("homeController"function($scope) {  
  14.     $scope.message = "Home Page";  
  15. }).controller("coursesController"function($scope) {  
  16.     $scope.courses = ["c#""SQL""Oracle"];  
  17. }).controller("studentsController"function($scope, $http) {  
  18.     $http.get("StudentService.asmx/GetAllStudents").then(function(response) {  
  19.         $scope.students = response.data;  
  20.     })  
  21. })  
Reference this script file to our main page and also in our HTML tag, write ng-app directive name as Demo.

Now, le'ts run the Application and we will see the screenshot, given below-

application

As you can see from the above output at the top of the URL, # appears, when you click on the URL. We will see, how to remove those and keep a clean URL.

In $locationprovider, provide the code, given below and set it to true-
  1. .config(function ($routeProvider,$locationProvider) {  
  2. $locationProvider.html5Mode(true);  
In the next step, we will remove all the # from index.html page, which we had tagged earlier in anchor tag.
  1. <a href="home">Home</a>  
  2. <a href="courses">Courses</a>  
  3. <a href="students">Students</a>  
The next step is in our web.config file, where we write the code, given below-
  1. <system.webServer>  
  2.     <rewrite>  
  3.         <rules>  
  4.             <rule name="RewriteRules" stopProcessing="true">  
  5.                 <match url=".*" />  
  6.                 <conditions logicalGrouping="MatchAll">  
  7.                     <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />  
  8.                     <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />  
  9.                     <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> </conditions>  
  10.                 <action type="Rewrite" url="/index.html" /> </rule>  
  11.         </rules>  
  12.     </rewrite>  
  13. </system.webServer>  
As it says any routing will redirect to index.html and there are some exceptions, where in a user requests for a file or a directory and by default, it will re-route to index.html page.

The last step is to include base in our page for a single Page Application, as given below- 

application

As the / says, it will search for the parent or the root directory and it will display index.html. Now, run the solution and you will see clean URL.

demo

Now, we will see the default route in AngularJS. Here, we will use the otherwise function in Angular JS. In this, we will just write otherwise and redirect to the following- 
  1. .otherwise({  
  2. redirectTO : "/home"  
  3. })  
If a user enters any value in URL, the default route is our Home page. 

Now, we will see AngularJS Intellisense in Visual Studio. In script.js file, we already have a reference to our file. Now, we will add Angularjs route reference in our script.js file.

When we type a .module in our script file, we get an extension. When we type .when, we don’t get a proper intellisense. To get a proper intellisense, we need to browse the URL, given below-

https://github.com/jmbledsoe/angularjs-visualstudio-intellisense/blob/master/src/Scripts/angular.intellisense.js

When you open this URL, you will get the script. Select the script, copy it and save it as angular.intellisense.js.

Now, just copy this js file and paste in the folder, given below-

C:\Program Files (x86)\Microsoft Visual Studio 14.0\JavaScript\References

Now, go back to our script.js and type in the Angular Service code as .when you will get an intellisense.

demo

Also, you will get all the intellisense, so that was pretty easy to get an intellisense in a script file. These were three simple steps to get an intellisense. 

Conclusion

Hence, this was about AngularJS routing with Webservice . Hope, this article was helpful !!


Similar Articles