How to access state params (ui-sref) without including them in URL propery of state in angularjs

3k views Asked by At

This question is might be similar to this but with different requirements. As I was not able to make comment (required 50 points) I am replicating the question.

I want to simply access the parameters sent from ui-sref in template inside the controller without mentioning them in state URL .

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:

state('home', {
      url: '/:foo',
      views: {
        '***whatIsThis***': {
          templateUrl: 'home.html',
          controller: 'MainRootCtrl'    
        },

    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? I want to get bar as well without adding it to URL

1

There are 1 answers

7
hon2a On

If some of your params are not supposed to show up in the URL, you need to combine url and params:

.state('home', {
    url: '/:foo',
    params: {
        foo: 'default value of foo',
        bar: 'default value of bar'
    },
    ...
})

and then use $stateParams properly:

.controller('SomeController', ['$scope', '$stateParams', function ($scope, $stateParams) {
    // ... (use $stateParams)
}])

(see documentation).


And, if you're still stuck, please take a look at this working codepen demo.