Tuesday, 28 March 2017

How to use routeparams in routing ?



STEPS
  • Pass the parameter (using binding expression) with the URL
  • Configure the route with parameter like,  <URL>/:<param> with corresponding template and controller
  • Define the controller with object $routeParams and use the passed parameters using this object

EXAMPLE
Main page
index.html in previous examples

TEMPLATES
students.html
<h1>Student List</h1>
<ul>
   <li ng-repeat="student in students">
        <a href="students/{{student.id}}">
            {{ student.name }}
       </a>
   </li>
</ul>

studentDetails.html
<h1>Student Details</h1>
<table>
  <tr>
     <td>Id</td>
     <td>{{ student.id }}</td>
  </tr>
  <tr>
     <td>Name</td>
     <td>{{ student.name }}</td>
  </tr>
  <tr>
     <td>Gender</td>
     <td>{{ student.gender }}</td>
  </tr>
</table>

<a href="students">List of students</a>




JS 
var app = angular.module("module1", ["ngRoute"]);
 
app.config( function ($routeProvider) {
   $routeProvider
    .when(
"/home", {
        templateUrl: "templates/home.html",
        controller: "homeController"
     })
    .when(
"/trainings", {
        templateUrl: "templates/trainings.html",
        controller: "trainingController"
    })
    .when(
"/students", {
       templateUrl: "templates/students.html",
       controller: "studentController"
    })

    .when("/students/:id", {
       templateUrl: "templates/studentDetails.html",
       controller: "studentDetailsController"
    })
});



app.controller("homeController", function ($scope) {
   $scope.message = "Welcome to Home page"
;
});

app.controller("trainingController", function ($scope) {
   $scope.trainings = ["AngularJS", "HTML", "CSS", "Javascript"]
;
});

app.controller("studentController", function ($scope, $http) {
   $http.get("service/api/GetAllStudents").then( function(response) {
      $scope.students = response.data
;
   })
});




app.controller("studentDetailsController", function ($scope, $http, $routeParams) {
   $http({

      url:"service/api/GetStudent",
      params:{ id:$routeParams.id },
      method:"get"
   })
   .then( function(response) {
      $scope.student = response.data
;
   })

 
});

No comments:

Post a Comment

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