Complete Guide to Parameter Passing with ui-sref in AngularJS UI-Router

Nov 20, 2025 · Programming · 12 views · 7.8

Keywords: AngularJS | UI-Router | Parameter_Passing | ui-sref | $stateParams

Abstract: This article provides a comprehensive exploration of parameter passing using the ui-sref directive in AngularJS UI-Router. By analyzing core concepts such as URL parameter definitions, $stateParams service usage, and params configuration objects, it offers complete solutions from basic to advanced levels. The article includes detailed code examples and configuration instructions to help developers resolve common parameter passing issues like undefined parameters and URL configuration errors.

UI-Router Parameter Passing Fundamentals

In AngularJS applications, UI-Router provides powerful state management capabilities, where parameter passing is a crucial aspect for implementing complex application logic. Through the ui-sref directive, developers can easily pass data between states, but proper configuration is essential for this functionality.

URL Parameter Definition

First, URL parameters need to be correctly configured in the state definition. UI-Router supports two main parameter definition approaches: through URL paths and query parameters.

$stateProvider
  .state('home', {
    url: '/:foo?bar',
    views: {
      '': {
        templateUrl: 'tpl.home.html',
        controller: 'MainRootCtrl'
      }
    }
  });

In the above configuration, url: '/:foo?bar' defines two types of parameters: foo as a path parameter and bar as an optional query parameter. This configuration corresponds to the URL format:

/fooValue?bar=barValue

Parameter Passing with ui-sref

When using the ui-sref directive to pass parameters, a parameter object needs to be added after the state name:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">Link 1</a>
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">Link 2</a>

When users click these links, UI-Router automatically constructs the corresponding URL and activates the target state, while passing the parameter values to the corresponding controller.

Parameter Retrieval in Controllers

In controllers, parameters need to be retrieved using the $stateParams service:

app.controller('MainRootCtrl', function($scope, $state, $stateParams) {
  var foo = $stateParams.foo; // Get fooVal
  var bar = $stateParams.bar; // Get barVal
  
  $scope.state = $state.current;
  $scope.params = $stateParams;
});

It's important to note that the service name is $stateParams (plural form), not $stateParam. This is a common mistake among beginners.

Advanced Parameter Configuration

UI-Router provides more granular parameter control mechanisms through the params configuration object for complex requirements:

.state('other', {
  url: '/other/:foo?bar',
  params: { 
    foo: {
      value: 'defaultValue',
      squash: false,
    },
    bar: { 
      array: true,
    },
    hiddenParam: 'YES',
  },
  // ... Other configurations
});

Detailed Parameter Configuration Options

value: Specifies the default value for the parameter. When the parameter value equals the default, UI-Router decides whether to display it in the URL based on the squash configuration.

array: When set to true, the parameter value is treated as an array. This is particularly useful for handling multi-value parameters, such as category filtering functionality.

squash: Configures how default parameter values are represented in the URL. When the current parameter value matches the default, squash determines whether to retain the parameter in the URL.

Usage of Non-URL Parameters

Through params configuration, parameters that don't appear in the URL can be defined:

.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'
    }
  },
  params: {
    foo: null,
    bar: null
  }
});

This configuration allows parameter passing programmatically:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go to Home</a>

Note that non-URL parameters are lost after page refresh since they are not stored in the URL.

Advanced Features of ui-sref Directive

The ui-sref directive supports various advanced configuration options through the ui-sref-opts attribute to control state transition behavior:

<a ui-sref="home" ui-sref-opts="{ reload: true }">Home</a>

Available options include:

Common Issues and Solutions

Undefined Parameter Issues

When obtaining undefined parameter values in controllers, it's typically caused by:

  1. Incorrect Service Name: Ensure using $stateParams instead of $stateParam
  2. URL Configuration Mismatch: Check if the URL pattern in state definition matches the passed parameters
  3. Parameter Name Inconsistency: Confirm parameter names in ui-sref match those in state definition

Parameter Handling in Multi-View States

In multi-view configurations, parameters are available to all view controllers:

.state('home', {
  url: '/:foo?bar',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'
    },
    'A@home': {
      templateUrl: 'a.html',
      controller: 'MainCtrl'
    },
    'B@home': {
      templateUrl: 'b.html',
      controller: 'SomeController'
    }
  }
});

In this configuration, all three controllers can access the same parameter values through $stateParams.

Best Practice Recommendations

Parameter Naming Conventions: Use meaningful parameter names and avoid overly abbreviated names.

Default Value Settings: Set reasonable default values for optional parameters to enhance application robustness.

Parameter Validation: Add parameter validation logic in controllers to ensure parameter value validity.

Error Handling: Implement appropriate error handling mechanisms to address missing or invalid parameters.

Conclusion

By properly configuring UI-Router state parameters, developers can build feature-rich single-page applications with excellent user experience. The key lies in understanding URL parameter definitions, $stateParams service usage, and advanced parameter configuration options. The examples and best practices provided in this article can help developers avoid common pitfalls and implement efficient parameter passing mechanisms.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.