Home > Web Front-end > JS Tutorial > How do I Pass Parameters to Controllers in UI-Router?

How do I Pass Parameters to Controllers in UI-Router?

Patricia Arquette
Release: 2024-11-08 08:56:02
Original
878 people have browsed it

How do I Pass Parameters to Controllers in UI-Router?

Passing Parameters to Controllers in UI-Router

In UI-Router, you can utilize the ui-sref directive to navigate between states and pass parameters to their controllers. To accomplish this, follow these steps:

Define Parameters in the State Configuration:

Modify your state definition to include the expected parameters as part of the URL:

.state('home', {
  url: '/:foo?bar', // Include parameters in the URL path
  ...
});
Copy after login

Access Parameters in the Controller:

In the controller, you can access the passed parameters via the $stateParams service. Ensure you use $stateParams instead of $stateParam.

app.controller('SomeController', function($scope, $stateParams) {
  var foo = $stateParams.foo;
  var bar = $stateParams.bar;
});     
Copy after login

Example:

Consider the following state definition:

.state('home', {
  url: '/',
  params: {
    foo: {
      value: 'fooVal',
      squash: false,
    },
  },
  ...
});
Copy after login

In this case, you can pass parameters to the home state using UI-SREF:

<a ui-sref="home({foo: 'customVal'})">Go to home state</a>
Copy after login

Additional Options Using params:

You can configure customized parameters using the params object in the state definition, including:

  • value: Specify a default value.
  • array: Treat the parameter as an array.
  • squash: Control how default values are represented in the URL.

Conclusion:

By following these steps, you can successfully pass parameters to controllers in UI-Router using ui-sref and access them using $stateParams.

The above is the detailed content of How do I Pass Parameters to Controllers in UI-Router?. 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