Home > Web Front-end > JS Tutorial > body text

How to Pass Parameters with ui-sref and Retrieve them in the Controller?

Mary-Kate Olsen
Release: 2024-11-06 15:37:03
Original
144 people have browsed it

How to Pass Parameters with ui-sref and Retrieve them in the Controller?

Passing Parameters with ui-sref and Retrieving in the Controller

Problem

You need to pass two parameters to a state using ui-sref and access them in the state controller. However, you encounter issues with undefined parameter values in the controller.

Solution

To pass parameters with ui-sref and retrieve them in the controller, follow these steps:

  1. Update State Definition:
$stateProvider
    .state('home', {
      url: '/:foo?bar', // Define parameter placeholders in the URL
      views: {
        '': {
          templateUrl: 'home.html',
          controller: 'MainRootCtrl'
        },
        ...
      }
    });
Copy after login
  1. Use $stateParams in the Controller:
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    var foo = $stateParams.foo; // Access fooVal
    var bar = $stateParams.bar; // Access barVal
})
Copy after login

Granular Parameter Configuration

In addition to URL parameter placeholders, you can also define granular parameters using the params object in state definitions:

.state('other', {
    url: '/other/:foo?bar',
    params: {
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        bar: {
          array: true,
        },
        hiddenParam: 'YES',
      }
    ...
Copy after login

Example Usage

To pass parameters using ui-sref and retrieve them with the updated state definition:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})"></a>
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})"></a>
Copy after login

Parameters Configuration Options

The params object settings include:

  • value: Specifies the default parameter value.
  • array: Treats the parameter as an array.
  • squash: Configures how default parameter values are represented in the URL.

For more information, refer to the ui-router documentation on URL Parameters and $stateProvider.

The above is the detailed content of How to Pass Parameters with ui-sref and Retrieve them in the Controller?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!