4

Based on the documentation, angularjs ui-router url parameters are by default optional. So is there a way to create mandatory parameters? Like when the parameter is missing or null it will not proceed to the page?

Hope you can help me.

Thanks

4
  • Why not 'if (typeof param === 'undefined') and then redirect? Commented Jun 10, 2016 at 23:10
  • or before in your template and just not show the link? Commented Jun 10, 2016 at 23:11
  • It's not on my view already. Also I can't do it on my controller, is there a way to do it while declaring the states? Commented Jun 10, 2016 at 23:15
  • Then I don't know. I think you should not load an init state with url parameters. Just redirect after the init in your init directive or controller Commented Jun 10, 2016 at 23:21

2 Answers 2

4

Use UI Routers resolve to check if route params are missing.

//Example of a single route
.state('dashboard', {
  url: '/dashboard/:userId',
  templateUrl: 'dashboard.html',
  controller: 'DashboardController',
  resolve: function($stateParams, $location){

    //Check if url parameter is missing.
    if ($stateParams.userId === undefined) {
      //Do something such as navigating to a different page.
      $location.path('/somewhere/else');
    }
  }
})
Sign up to request clarification or add additional context in comments.

4 Comments

It doesn't work when the scripts are minified. Do you have any idea?
That is not good. Apologies. Try removing the [] wrapping the resolve function.
For future reference, instead of removing the [], I did it the way AngularJS wants it to be: resolve : ['$stateParams', '$location', function($stateParams, $location){ //body here }]
resolve is an object with keys and values. It should be resolve: { somekey: function($stateParams, $location){ ... } }.
2

Above answer prasents incorrect usage of resolve that will fail when code is minified even if annotated. Look at this issue I've spent a lot of time debugging this, because [email protected] won't warn you that resolve should be object.

resolve: { 
    somekey: function($stateParams, $location){

        //Check if url parameter is missing.
        if ($stateParams.userId === undefined) {
          //Do something such as navigating to a different page.
          $location.path('/somewhere/else');
    }
}

If you need minification, ngAnnotate

1 Comment

You are missing an end bracket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.