Here's an example to show how to. Updated state definition:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
And this will be the controller:
.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;
})
You can observe that the state home now has url defined as:
url: '/:foo?bar',
that means, the params in url are expected as
/fooVal?bar=barValue
Below two links will correctly pass arguments into the controller:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
Also, the controller does consume $stateParams instead of $stateParam.
Link to document is as follows:
You can refer to this:
http://plnkr.co/edit/r2JhV4PcYpKJdBCwHIWS?p=preview
params : {}
There is also new, more granular setting params: {}. As we've already seen, we can declare parameters as part of url. But with params: {} configuration - we can extend this definition or even introduce parameters which are not part of the URL:
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
Settings are available for params are described in the documentation of the $stateProvider
Below is just an extract
value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.
We can call these params this way:
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
Are you searching for a good course in Angular? Then have a look at the Angular Certification course from Intellipaat!