Home > Article > Web Front-end > How to Pass Parameters to a Controller Using ui-sref in UI-Router?
Passing Parameters to Controller Using ui-sref in UI-Router
In UI-Router, passing parameters to a controller through ui-sref is a crucial element for sharing data between states. Here's how to accomplish this task effectively:
To begin, define the URL of the target state to include parameter placeholders using the colon syntax, as seen in the updated state definition shown below:
$stateProvider .state('home', { url: '/:foo?bar', ...
In this example, the 'home' state expects parameters 'foo' and 'bar' in the URL path.
Next, adjust the controller to receive these parameters correctly:
.controller('MainRootCtrl', function($scope, $state, $stateParams) { // ... var foo = $stateParams.foo; // Accessing 'fooVal' var bar = $stateParams.bar; // Accessing 'barVal' // ...
In this controller, we inject $stateParams instead of $stateParam, which gives us access to the passed parameters.
Moreover, UI-Router also provides fine-grained parameter configuration through the 'params' object within the state definition. This option allows you to specify default values, impose type constraints, and more.
For instance, consider this extended parameter configuration:
.state('other', { url: '/other/:foo?bar', params: { foo: { value: 'defaultValue', squash: false, }, bar: { array: true, // Treat bar as an array }, hiddenParam: 'YES', // Not present in the URL }, ...
This configuration shows how we can define default values for parameters and control their behavior in the URL.
Finally, remember to pass the parameters when navigating to the desired state using either the 'ui-sref' attribute or '$state.go()' method:
<a ui-sref="other({foo: 'fooVal1', bar: 'barVal1'})">...</a> $state.go('home', {foo: 'fooVal2', bar: 'barVal2'});
By implementing this approach, you can efficiently pass parameters to controllers using ui-sref in UI-Router, ensuring seamless state transitions and data sharing within your AngularJS applications.
The above is the detailed content of How to Pass Parameters to a Controller Using ui-sref in UI-Router?. For more information, please follow other related articles on the PHP Chinese website!