Tuesday, 18 April 2017

How to use optional URL parameters ?


1. Add a search button on HTML to collect the searched name.
Name : <input type="text" ng-model="studentCtrl.name">
<button ng-click="studentCtrl.searchStudent()">Search</button>


2. Route config with Optional param "name" for new template for search and a controller

$routeProvider
   .when("
/studentSearch/:name?", {
      templateUrl: "templates/studentSearchDetails.html",
      controller: "
studentSearchController",
      controllerAs: "studentSearchCtrl"
   }

 

3. studentController will check searched value and call the new route defined

app.controller("studentController", function ($route, $http, $location) {
   var curr = this;
   curr.reloadData = function() {
      $route.reload();
   }
 

   curr.searchStudent = function() {
      if (curr.name) {

         $location.url("/studentSearch/" + curr.name);
      } else {
         $location.url("/studentSearch");
      }
   }


   $http.get("service/api/GetAllStudents").then(
     function(response) {
        curr.students = response.data
;
     }
   )
});



4. studentSearchController will check searched value and call the backend API to load data

app.controller("studentSearchController", function ($http, $routeParams) {
   var curr = this;


   if($routeParams.name) {
        $http({
        url: "service/api/GetStudentsByName",
        method: "get",
        params: { name: $routeParams.name }
     }).then(
        function(response) {
          curr.students = response.data
;
        }
     )

  } else {
     $http.get("service/api/GetAllStudents").then(
        function(response) {
           curr.students = response.data
;
        }
     )

  }
 
});



No comments:

Post a Comment

Note: only a member of this blog may post a comment.