Angular UI Router Required URL Parameter?

I have several states that use the same controller. Some of them do not require a URL parameter, and some. How to avoid access to state if URL parameter is not specified?

Example:

I have 2 types or states, a list and a single. They both have the same controller. I have routes displayed as follows:

state: app.list
url: /list
controller: appCtrl

state: app.single
url: /single/:id
controller: appCtrl

Now I want it to singlebe available only if an identifier is specified, another wise redirect to another page. How is this possible using the same controller?

+4
source share
1 answer

Approach 1

$urlRouterProvider when() .

app.config(function($urlRouterProvider){
    // when there is an single route without param, redirect to /list
      $urlRouterProvider.when('/single/:id', ['$match', '$state', function($match, $state) {
          if($match.id === ""){
             $state.transitionTo("app.list");
          }
       }
      ]);
});

: http://plnkr.co/edit/sEoUGGCEge0XbKp3nQnc?p=preview

2

param controller

myApp.controller('MainCtrl', function($state, $stateParams) {
  if($state.current.name == 'app.single' && $stateParams.id === ""){
    $state.transitionTo("app.list");
  }
});

: http://plnkr.co/edit/QNF1RHy4Prde4CRhNLFa?p=preview

. , app.single. , , app.single param. main, without param of single state. list.

+3

All Articles