Route parameters ($routeParams) in AngularJS

Loading

$routeParams is a built-in service in AngularJS that allows us to retrieve parameters from the URL when using AngularJS routing (ngRoute). It is especially useful when dealing with dynamic routes that require user-specific or context-specific data.

Why Use $routeParams?

Retrieves dynamic values from the URL.
Helps in passing data between views without global variables.
Essential for creating user profiles, product pages, or blog posts dynamically.
Works seamlessly with $routeProvider.


2. Setting Up $routeParams

To use $routeParams, you must first set up AngularJS routing using ngRoute.

Step 1: Include AngularJS and ngRoute

Make sure you include AngularJS and the angular-route.js file in your project.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.js"></script>

3. Defining Routes with Parameters

You need to configure $routeProvider to define dynamic routes.

Step 2: Configure Routes

var app = angular.module("myApp", ["ngRoute"]);

app.config(function($routeProvider) {
$routeProvider
.when("/user/:id", {
templateUrl: "user.html",
controller: "UserController"
})
.when("/product/:category/:productId", {
templateUrl: "product.html",
controller: "ProductController"
})
.otherwise({
redirectTo: "/"
});
});

Explanation:

  • /user/:id → Captures id from the URL (e.g., /user/101id = 101).
  • /product/:category/:productId → Captures two parameters (category and productId).

4. Retrieving Route Parameters in Controllers

Once the parameters are defined, we can access them inside controllers using $routeParams.

Step 3: Create UserController

app.controller("UserController", function($scope, $routeParams) {
$scope.userId = $routeParams.id;
});

Step 4: Create user.html

<h2>User Profile</h2>
<p>User ID: {{ userId }}</p>

Example URL:

http://example.com/#!/user/5

Output on Page:

User ID: 5

5. Using Multiple Route Parameters

You can define routes with multiple dynamic parameters.

Step 5: Create ProductController

app.controller("ProductController", function($scope, $routeParams) {
$scope.category = $routeParams.category;
$scope.productId = $routeParams.productId;
});

Step 6: Create product.html

<h2>Product Details</h2>
<p>Category: {{ category }}</p>
<p>Product ID: {{ productId }}</p>

Example URL:

http://example.com/#!/product/electronics/42

Output on Page:

Category: electronics
Product ID: 42

6. Using $routeParams with API Calls

You can use $routeParams to fetch data from an API based on the dynamic values.

Step 7: Fetch User Data from API

app.controller("UserController", function($scope, $routeParams, $http) {
$scope.userId = $routeParams.id;

$http.get("https://api.example.com/users/" + $scope.userId)
.then(function(response) {
$scope.user = response.data;
});
});

Step 8: Modify user.html

<h2>User Profile</h2>
<p>User ID: {{ userId }}</p>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>

This method dynamically loads user details when navigating to /user/:id.


7. Handling Route Parameter Changes

If the route parameter changes without a full reload, AngularJS does not automatically update the controller. You can use $watch to detect changes.

Step 9: Watch for Parameter Changes

app.controller("UserController", function($scope, $routeParams) {
$scope.userId = $routeParams.id;

$scope.$watch(function() {
return $routeParams.id;
}, function(newId) {
$scope.userId = newId;
});
});

This ensures that userId updates whenever the route changes.


8. Redirecting Based on Route Parameters

You can redirect users based on route parameters using $location.path().

Step 10: Redirect If ID Is Missing

app.controller("UserController", function($scope, $routeParams, $location) {
if (!$routeParams.id) {
$location.path("/");
}
});

If the id is not provided in the URL, it will redirect to the home page.


9. Handling Invalid Route Parameters

You can check if a parameter is valid before displaying the page.

Step 11: Validate ID

app.controller("UserController", function($scope, $routeParams, $location) {
$scope.userId = $routeParams.id;

// Validate if ID is a number
if (isNaN($scope.userId)) {
alert("Invalid User ID!");
$location.path("/");
}
});

If the user enters an invalid ID (e.g., /user/abc), an alert is shown, and they are redirected.


10. Using $routeParams Inside Services

You can access $routeParams inside a service.

Step 12: Create UserService

app.service("UserService", function($http) {
this.getUser = function(userId) {
return $http.get("https://api.example.com/users/" + userId);
};
});

Step 13: Inject into Controller

app.controller("UserController", function($scope, $routeParams, UserService) {
$scope.userId = $routeParams.id;

UserService.getUser($scope.userId).then(function(response) {
$scope.user = response.data;
});
});

This approach keeps the API call logic separate from the controller.

Leave a Reply

Your email address will not be published. Required fields are marked *