In this tutorial, we will explore how to pass parameters using ui-sref
in ui-router
to the controller in an AngularJS application.
AngularJS UI-Router provides a powerful way to handle routing and state management in your AngularJS applications. One common requirement is to pass parameters from a view to a controller when navigating between states. This tutorial will guide you on how to achieve this using ui-sref
in UI-Router.
Updated State Definition
The key to passing parameters lies in the configuration of states. The updated state definition in the $stateProvider
looks like this:
$stateProvider .state('home', { url: '/:foo?bar', views: { '': { templateUrl: 'tpl.home.html', controller: 'MainRootCtrl' }, // ... other views can be defined here } });
Here, the url
property is defined as /:foo?bar
, indicating that the expected parameters in the URL are /fooVal?bar=barValue
.
Controller Configuration
The controller associated with the ‘home’ state can access these parameters as follows:
.controller('MainRootCtrl', function($scope, $state, $stateParams) { //... var foo = $stateParams.foo; //getting fooVal var bar = $stateParams.bar; //getting barVal //... $scope.state = $state.current; $scope.params = $stateParams; });
Here, $stateParams
is used to retrieve the values of foo
and bar
from the URL.
ui-sref
Usage
To correctly pass arguments into the controller, you can use ui-sref
in your HTML:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">Link 1</a> <a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">Link 2</a>
These links demonstrate how to pass values for foo
and bar
into the ‘home’ state.
Additional Configuration – params
Property
The params
property in the state definition allows more granular control over parameters, including setting default values and specifying whether parameters should be part of the URL. Here’s an example:
.state('other', { url: '/other/:foo?bar', params: { foo: { value: 'defaultValue', squash: false, }, bar: { array: true, }, hiddenParam: 'YES', }, // ... other state configurations });
This example showcases setting default values for foo
, treating bar
as an array, and introducing a parameter (hiddenParam
) not included in the URL.
Non-URL Parameter Configuration
You don’t necessarily need to have parameters inside the URL. Instead, you can configure the state like this:
$stateProvider .state('home', { url: '/', views: { '': { templateUrl: 'home.html', controller: 'MainRootCtrl' }, }, params: { foo: null, bar: null } });
This allows you to send parameters to the state using either $state.go
or ui-sref
.
Note on $stateParams
vs $stateParam
A common mistake is misspelling $stateParams
as $stateParam
. Ensure the correct usage to avoid getting undefined
values.
Conclusion
This tutorial provides a comprehensive guide on passing parameters using ui-sref
in ui-router
to the controller in AngularJS. It covers state and controller configurations, usage of ui-sref
, additional parameter settings, and common pitfalls.