Shawn
Shawn

Reputation: 2735

Angular UI Router - How to make a parameter required

$stateProvider.state('state1', {
    url:'/state1/:param1/and/{param2:.+}',
    templateUrl: 'state1.html',
    controller: 'State1Controller',
});

I'm trying to make param2 required by using regex as seen above. If it's empty, then the default state should load:

    $urlRouterProvider.otherwise("/");

    $stateProvider.state('otherwise',{
        url: '/',
        templateUrl:'default.html'
    });

Now the results:

state1/1/and/1 goes to state1. Good.

state1/1/and goes to otherwise. Good.

But,

state1/1/and/ goes to no state! Neither states are loaded. It's not redirecting back to /. What?!

How do I properly make a parameter required?

Upvotes: 2

Views: 294

Answers (1)

Glen Pinheiro
Glen Pinheiro

Reputation: 216

Angular js ui-router url parameters are optional by default. For your case above we could make use of $stateParams to check if the required parameter is defined or not. Please check the code below.

if ($stateParams.param2=== undefined) {
  // Navigate to home.
  $location.path('/');
}

Hope this would solve your issue. Thanks.

Upvotes: 1

Related Questions