Home  >  Article  >  Web Front-end  >  How can I Pass Parameters to Controllers Using ui-sref in ui-router?

How can I Pass Parameters to Controllers Using ui-sref in ui-router?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 18:56:02574browse

How can I Pass Parameters to Controllers Using ui-sref in ui-router?

Passing Parameters to Controllers Using ui-sref in ui-router

In ui-router, using ui-sref to transition to a state allows for the passing of parameters to the controller. To clarify, you can send and receive two parameters, "foo" and "bar," to a target state.

State Definition

Update the state definition to accept parameters in the URL:

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

Controller Consumption

Within the controller, retrieve the parameters from $stateParams:

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

Link Generation

To pass the parameters, use this syntax:

<a ui-sref="home({foo: 'fooVal', bar: 'barVal'})">

This will transition to the 'home' state with the specified foo and bar parameters, which can then be accessed in the controller via $stateParams.

Customizing Parameters (Optional)

With the "params" property in the state definition, you can further configure parameter behavior:

  $stateProvider
    .state('other', {
      url: '/other/:foo?bar',
      params: {
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        bar: {
          array: true,
        },
        hiddenParam: 'YES',
        // (not in URL)
      }
    });

Parameter settings include:

  • value: Default value
  • array: Treat parameter value as an array
  • squash: Control default value representation in URL

Parameter Injection

Controller parameter injection is done via $stateParams. You can retrieve values with:

var paramValue = $stateParams.paramName;

This is how UI-router enables parameter passing between states using ui-sref for easy state transitions and parameter accessibility in the controller.

The above is the detailed content of How can I Pass Parameters to Controllers Using ui-sref in ui-router?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn