Home > Article > Web Front-end > 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:
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!