Passing parameters between routes using $stateParams

Loading

In AngularJS, $stateParams is an integral part of the UI Router module that helps pass parameters between different routes or states. Parameters can be embedded in the route URL, making it possible to access them easily in different views or controllers. This feature allows you to make your application dynamic and tailor the content based on specific user inputs, such as IDs or query parameters.

Step-by-Step Guide: Passing Parameters Between Routes Using $stateParams

Step 1: Setting Up AngularJS and UI Router

To begin, make sure you have both AngularJS and the ui-router library included in your project. Here’s a basic HTML setup for your application:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Passing Parameters Between Routes</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
</head>
<body ng-app="myApp">
<div>
<a ui-sref="home">Go to Home</a>
<a ui-sref="profile({ userId: 123 })">Go to Profile with ID 123</a>
</div>
<div ui-view></div> <!-- UI View for the content -->

<script src="app.js"></script>
</body>
</html>

In this setup, there are links for navigating to different states: the home page and the profile page with a parameter (userId).

Step 2: Create the AngularJS Module and Configure Routes

In the app.js file, set up your AngularJS module, configure the routes using $stateProvider, and pass parameters through the URL.

var app = angular.module('myApp', ['ui.router']);

app.config(function($stateProvider, $urlRouterProvider) {
// Default route if the URL doesn't match any state
$urlRouterProvider.otherwise('/home');

// Define the states
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('profile', {
url: '/profile/:userId', // Parameterized URL
templateUrl: 'profile.html',
controller: 'ProfileController'
});
});
  • home state: This is a simple state where no parameters are passed.
  • profile state: This state has a parameter userId in the URL, indicated by :userId. This will be passed when navigating to the profile page.

Step 3: Define the Controllers

Now, let’s define the controllers that will be used for these views.

app.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home Page!";
});

app.controller('ProfileController', function($scope, $stateParams) {
// Access the userId parameter passed in the URL
$scope.userId = $stateParams.userId;
});
  • HomeController: Simply sets a welcome message.
  • ProfileController: Accesses the userId parameter using $stateParams.userId and displays it.

Step 4: Create the HTML Templates

Create the HTML files corresponding to each view.

  1. home.html
<div>
<h1>Home Page</h1>
<p>{{ message }}</p>
<a ui-sref="profile({ userId: 123 })">Go to Profile with ID 123</a>
</div>
  1. profile.html
<div>
<h1>Profile Page</h1>
<p>User ID: {{ userId }}</p>
</div>

In the home.html file, there’s a link that navigates to the profile state, passing the userId as a parameter (123). The profile.html file displays the userId that was passed via the URL.

Step 5: Navigating Between Routes with Parameters

In AngularJS, you can navigate between states using the ui-sref directive. This directive binds a link to a route and can pass parameters as well. Here’s how it works:

<a ui-sref="profile({ userId: 123 })">Go to Profile with ID 123</a>

When the user clicks on this link, the application navigates to the profile state, and the userId parameter (123) is passed as part of the URL.

Step 6: Retrieving Parameters Using $stateParams

Once the application navigates to the profile page, the controller for the profile state will receive the parameter userId via $stateParams.

  • The ProfileController retrieves the value of userId from $stateParams:
$scope.userId = $stateParams.userId;
  • This value is then displayed on the profile page using AngularJS data binding.

Step 7: Handling Optional Parameters

In some cases, you may want to pass parameters that are optional. You can define default values or check if the parameter exists within the controller. For example, you could handle missing parameters as follows:

app.controller('ProfileController', function($scope, $stateParams) {
$scope.userId = $stateParams.userId || 'No user ID provided';
});

Here, if userId is not passed in the URL, it will default to 'No user ID provided'.

Step 8: Using Query Parameters

While $stateParams is typically used to capture URL parameters, you can also use query parameters. For example, if the URL contains query parameters like ?ref=dashboard, you can retrieve them using AngularJS’s $location service.

Example URL: /profile/123?ref=dashboard

In your controller:

app.controller('ProfileController', function($scope, $stateParams, $location) {
$scope.userId = $stateParams.userId;
$scope.referrer = $location.search().ref; // Extracting the 'ref' query parameter
});

Here, $location.search() will return the query parameters as an object, and you can access them by key (e.g., ref).

Step 9: Summary of Key Points

  • Passing Parameters: Use :parameterName in the state’s URL to pass parameters, and access them in the controller using $stateParams.
  • Optional Parameters: Use conditional logic to handle missing parameters.
  • Query Parameters: Use $location.search() for query parameters in the URL.
  • State Transitions: Use ui-sref to navigate between states and pass parameters.
  • Dynamic Content: Parameters allow dynamic content in your views by passing data from one state to another.

Leave a Reply

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