AngularJS Optional URL Parameters

Overview

In this article, we will see optional URL parameters in AngularJS, with an example. We will be using the same example demo application where we had displayed the list of students. In that, we had displayed the list of students from  the database with the help of web services.

For more articles on AngularJS refer these links,

Introduction

At the moment, we are in studentController displaying the list of students.

students

I want to include a search criteria to display the names of the students and their respective details. So, we will modify our code in web services. 

We will add another web method which will search the students by name .

So, here is the change.
  1. [WebMethod]  
  2.         public void GetStudentsByName(string name)  
  3.         {  
  4.             List<Student> listStudents = new List<Student>();  
  5.             string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;  
  6.             using (SqlConnection con = new SqlConnection(cs))  
  7.             {  
  8.                 SqlCommand cmd = new SqlCommand("select * from students where name like @name", con);  
  9.                 SqlParameter param = new SqlParameter()  
  10.                 {  
  11.                     ParameterName="@name",  
  12.                     Value=name + "%"  
  13.                 };  
  14.                 cmd.Parameters.Add(param);  
  15.                 con.Open();  
  16.                 SqlDataReader sdr = cmd.ExecuteReader();  
  17.                 while (sdr.Read())  
  18.                 {  
  19.                     Student student = new Student();  
  20.                     student.id = Convert.ToInt32(sdr["id"]);  
  21.                     student.name = sdr["Name"].ToString();  
  22.                     student.gender = sdr["gender"].ToString();  
  23.                     student.city = sdr["city"].ToString();  
  24.                     listStudents.Add(student);  
  25.   
  26.   
  27.                 }  
  28.   
  29.             }  
  30.   
  31.             JavaScriptSerializer js = new JavaScriptSerializer();  
  32.             Context.Response.Write(js.Serialize(listStudents));  
  33.         }  
The function name here is GetStudentsByName. Passing the parameter namehas now modified the search query. Now, we have passed the parameter as @name and used sqlparamater to initialize those parameters.

Let’s save those changes and check our web service.

web service

Click on GetStudentsByName and type any name there.

GetStudentsByName

It should display the details i.e. list of students.

details

So, our web service is working properly here. This was our first change. Now, the next change is our Controller. We want that Controller to search by name. This is our studentsController.
  1. .controller("studentsController"function ($http, $route) {  
  2.                
  3.                   var vm = this;  
  4.   
  5.                   vm.reloadData = function () {  
  6.                       $route.reload();  
  7.                   }  
  8.                   $http.get("StudentService.asmx/GetAllStudents")  
  9.                   .then(function (response) {  
  10.                       vm.students = response.data;  
  11.                   })  
  12.                     })  
We will add SearchStudent method here in the studentsController. We will be using built-in service of Angular i.e. $location. Let’s see how.
  1. .controller("studentsController"function ($http, $route,$location) {  
  2.               
  3.                  vm.searchStudents = function () {  
  4.                      if (vm.name) {  
  5.                          $location.url("/studentsSearch/" + vm.name);  
  6.                      }  
  7.                      else {  
  8.                          $location.url("/studentsSearch/" );  
  9.                      }  
  10.   
  11.                  }  
searchStudent here is the method and in that, we will use a function and check the condition for true or false. If the variable contains name, then it will redirect to the URL as /studentsSearch/. We have appended that, else it will redirect to the same page that we had achieved by using $location.url .

Now, our final studentsController code is.
  1. .controller("studentsController"function ($http, $route,$location) {  
  2.                  
  3.                     vm.searchStudents = function () {  
  4.                         if (vm.name) {  
  5.                             $location.url("/studentsSearch/" + vm.name);  
  6.                         }  
  7.                         else {  
  8.                             $location.url("/studentsSearch/" );  
  9.                         }  
  10.   
  11.                     }  
  12.                     var vm = this;  
  13.   
  14.                     vm.reloadData = function () {  
  15.                         $route.reload();  
  16.                     }  
  17.                     $http.get("StudentService.asmx/GetAllStudents")  
  18.                     .then(function (response) {  
  19.                         vm.students = response.data;  
  20.                     })  
  21.                       })  
Now, our next change is to change the students.html page where we had to add a button in students.html page.

Name : <input tye="text" ng-model="name" />

The model for this will be same as the name of the student. Since we are using Controller as syntax, let's prefix that.

Name : <input tye="text" ng-model="studentsCtrl.name" />

Now, let’s add a button to this.
  1. <button ng-click="studentsCtrl.searchStudents">SearchBy</button>  
As our next change, we need to add one more Controller searchStudents.
  1. .controller("studentsSearchController"function ($http, $routeParams) {  
  2.     var vm = this;  
  3.   
  4.     if ($routeParams.name) {  
  5.         $http({  
  6.             url: "StudentService.asmx/GetStudentsByName",  
  7.             params: { name: $routeParams.name },  
  8.              
  9.         })  
  10. .then(function (response) {  
  11.     vm.students = response.data;  
  12. })  
  13.     }  
  14.     else {  
  15.         $http.get("StudentService.asmx/GetAllStudents")  
  16.                  .then(function (response) {  
  17.                      vm.students = response.data;  
  18.                  })  
  19.     }  
  20.       
  21. });  
We have added another Controller called searchStudentsScontroller and specified the routeparams in that. We use if condition here. If the search condition is true, it will display the data which we had written a new web method in our service. Else, it will display the list of all students.

The next step is to add route in our Controller. So, copy paste the code.
  1. .when("/studentsSearch/:name?", {  
  2.                                       templateUrl: "Templates/studentsSearch.html",  
  3.                                       controller: "studentsSearchController as studentsSearchCtrl"  
  4.                                   })  
Here, we are searching by name parameter in AngularJS. To search by optional URL parameter, you have to specify it. We are using Controller as syntax. We are specifying this as - 

controller: "studentsSearchController as studentsSearchCtrl"

So, our final Controller code is.
  1. /// <reference path="angular.min.js" />  
  2. /// <reference path="angular-route.min.js" />  
  3.   
  4. var app = angular.module("Demo", ["ngRoute"])  
  5.                     .config(function ($routeProvider, $locationProvider) {  
  6.                         $routeProvider.caseInsensitiveMatch = true;  
  7.   
  8.                         $routeProvider  
  9.   
  10.                         .when("/home", {  
  11.                             template: "<h1>Hello There !!</h1>",  
  12.                             controller: "homeController as homeCtrl"  
  13.                         })  
  14.   
  15.                           .when("/courses", {  
  16.                               templateUrl: "Templates/courses.html",  
  17.                               controller: "coursesController as coursesCtrl",  
  18.                                
  19.                           })  
  20.   
  21.                            .when("/students", {  
  22.                                templateUrl: "Templates/students.html",  
  23.                                controller: "studentsController as studentsCtrl"  
  24.                            })  
  25.   
  26.                                 .when("/students/:id", {  
  27.                                     templateUrl: "Templates/StudentDetail.html",  
  28.                                     controller: "StudentDetailController as StudentDetailCtrl"  
  29.                                 })  
  30.   
  31.                                   .when("/studentsSearch/:name?", {  
  32.                                       templateUrl: "Templates/studentsSearch.html",  
  33.                                       controller: "studentsSearchController as studentsSearchCtrl"  
  34.                                   })  
  35.                         .otherwise({  
  36.                             redirectTo: "/home"  
  37.                         })  
  38.                         $locationProvider.html5Mode(true);  
  39.                     })  
  40.   
  41.                 .controller("homeController"function () {  
  42.                     this.message = "Home Page";  
  43.                 })  
  44.   
  45.                  .controller("coursesController"function () {  
  46.                      this.courses = ["c#""SQL""Oracle"];  
  47.                  })  
  48.   
  49.                 .controller("studentsController"function ($http, $route,$location) {  
  50.                     var vm = this;  
  51.                     vm.searchStudents = function () {  
  52.                         if (vm.name) {  
  53.                             $location.url("/studentsSearch/" + vm.name);  
  54.                         }  
  55.                         else {  
  56.                             $location.url("/studentsSearch/" );  
  57.                         }  
  58.   
  59.                     }  
  60.                 
  61.   
  62.                     vm.reloadData = function () {  
  63.                         $route.reload();  
  64.                     }  
  65.                     $http.get("StudentService.asmx/GetAllStudents")  
  66.                     .then(function (response) {  
  67.                         vm.students = response.data;  
  68.                     })  
  69.                       })  
  70.       .controller("StudentDetailController"function ( $http, $routeParams) {  
  71.           var vm = this;  
  72.           $http({  
  73.           url: "StudentService.asmx/GetStudents",  
  74.           params: { id: $routeParams.id },  
  75.           method:"get"  
  76.       })  
  77.       .then(function (response) {  
  78.           vm.student = response.data;  
  79.       })  
  80.       })  
  81.   
  82. .controller("studentsSearchController"function ($http, $routeParams) {  
  83.     var vm = this;  
  84.   
  85.     if ($routeParams.name) {  
  86.         $http({  
  87.             url: "StudentService.asmx/GetStudentsByName",  
  88.             params: { name: $routeParams.name },  
  89.              
  90.         })  
  91. .then(function (response) {  
  92.     vm.students = response.data;  
  93. })  
  94.     }  
  95.     else {  
  96.         $http.get("StudentService.asmx/GetAllStudents")  
  97.                  .then(function (response) {  
  98.                      vm.students = response.data;  
  99.                  })  
  100.     }  
  101.       
  102. });  
Now, the last step is to add a partial template as studentsSearch.html page in templates folder. Add a page in Templates folder and name it as studentsSearch.html . Paste the following code there.
  1. <h1>Students Details</h1>  
  2. <table border="1" style="border-collapse:collapse">  
  3.     <thead>  
  4.         <tr>  
  5.             <th>  
  6.                 Id  
  7.             </th>  
  8.             <th>  
  9.                 Name  
  10.             </th>  
  11.             <th>  
  12.                 Gender  
  13.             </th>  
  14.             <th>  
  15.                 City  
  16.             </th>  
  17.         </tr>  
  18.     </thead>  
  19.   
  20.     <tr ng-repeat="student in studentsSearchCtrl.students">  
  21.         <td>{{student.id}}</td>  
  22.         <td>{{student.name}}</td>  
  23.         <td>{{student.gender}}</td>  
  24.         <td>{{student.city}}</td>  
  25.     </tr>  
  26. </table>  
We are looping thorough the records. We used ng-repeat directive here and we are using Controller as syntax. Now, we are initializing those students.

Save the Changes and reload the page. You will see the following:

page

Just type any record there and see the output.

output

When you click on search, you will see this output.

output

Notice the URL the search which I had typed had appeared in the URL and our partial template has loaded properly with respective details.

Now, let’s click on search button and see what output we do get.

output

output

We have got all the details of all students, that means if we don’t enter any name and click on search button, details of all the students are displayed. This means, in our Controller, we have mentioned else condition to display all the details of the students. So, this condition also gets satisfied.

Conclusion

This was all about optional URL Parameters in AngularJS. Hope this article was helpful!! 


Similar Articles