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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 08:56:02761browse

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
  ...
});

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;
});     

Example:

Consider the following state definition:

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

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>

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!

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