Jed
Jed

Reputation: 1074

AngularJS ui router mandatory parameters

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

Upvotes: 4

Views: 2977

Answers (2)

Alexander
Alexander

Reputation: 81

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

Upvotes: 2

Gregg
Gregg

Reputation: 667

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');
    }
  }
})

Upvotes: 4

Related Questions