[javascript] How to pass parameters using ui-sref in ui-router to controller

I need to pass and recieve two parameters to the state I want to transit to using ui-sref of ui-router.

Something like using the link below for transitioning the state to home with foo and bar parameters:

<a ui-sref="home({foo: 'fooVal', bar: 'barVal'})">Go to home state with foo and bar parameters </a>

Receiving foo and bar values in a controller:

app.controller('SomeController', function($scope, $stateParam) {
  //..
  var foo = $stateParam.foo; //getting fooVal
  var bar = $stateParam.bar; //getting barVal
  //..
});     

I get undefined for $stateParam in the controller.

Could somebody help me understand how to get it done?

Edit:

.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },

    'A@home': {
      templateUrl: 'a.html',
      controller: 'MainCtrl'
    },

    'B@home': {
      templateUrl: 'b.html',
      controller: 'SomeController'
    }
  }

});

This question is related to javascript html angularjs angular-ui-router angular-ui

The answer is


I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would 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; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These 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 doc:

You can check it here

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 paramters 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 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&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here


You don't necessarily need to have the parameters inside the URL.

For instance, with:

$stateProvider
.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },
  },
  params: {
    foo: null,
    bar: null
  }
})

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.


You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angular-ui-router

how to refresh page in angular 2 Could not resolve '...' from state '' AngularJS ui router passing data between states without URL What is the difference between $routeProvider and $stateProvider? How to pass parameters using ui-sref in ui-router to controller Exposing the current state name with ui router Clear History and Reload Page on Login/Logout Using Ionic Framework Using $window or $location to Redirect in AngularJS AngularJS UI Router - change url without reloading state `ui-router` $stateParams vs. $state.params

Examples related to angular-ui

Angular ui-grid dynamically calculate height of the grid How to pass parameters using ui-sref in ui-router to controller Angular bootstrap datepicker date format does not format ng-model value How to detect browser using angularjs? Injecting $scope into an angular service function() How to reload the current state? How to achieve pagination/table layout with Angular.js? How to use a keypress event in AngularJS? How to detect current state within directive Check if a input box is empty