Provide an optional attribute in the angular ui-router url

Is there a way to have an optional attribute at the beginning of the url in ui-router? If so, how?

I want to achieve this like this:

.state('events',{ url: '(/city:)?/events/:id' ... }) 

So "city" will be optional.

Thanks for any input.

+5
source share
3 answers

Probably the wrong practice is for two separate routes to point to the same state, but nothing prevents you from creating two different states that use the same permissions / controller / pattern.

 $stateProvider .state('state1', { url: "/:city/events/:id", templateUrl: "partials/events.html", controller: eventsCtrl }) .state('state2', { url: "/events/:id", templateUrl: "partials/events.html", controller: eventsCtrl }); function eventsCtrl($scope){ // shared controller } 

Again, this is probably bad practice, but I can't come up with a better solution.

+7
source

I tried to answer a similar one (if not one):

Angular js - route-ui add default cart

There is a working plunker , solving the problem for language , and not for city (but the concept is the same)

so we must / must introduce some super-standing "root".

In our case, we can even use some regular expression to limit the allowed values โ€‹โ€‹- because it would be difficult to guess what city is and what events

 .state('root', { url: '/{city:(?:Prague|Bristol|Denver)}', abstract: true, template: '<div ui-view=""></div>', params: {lang : { squash : true, value: 'Prague' }} }) 

It is important to install params : {} . It says that the default is Prague, so it will be a city if none are selected. It is also important - it must be crushed, skipped, if there is a match with the value of the "Prague" parameter :

 params: {lang : { squash : true, value: 'Prague' }} 

Now we can enter some nested state (s) that would declare root as the parent:

 .state('events',{ parent: 'root', url: '/events/:id' ... }) 

Check out the working example (with language instead of city) here . See Original Q and A for more details.

+7
source

I see no reason why you are not doing this in the standard ui-router state setting.

Demo

JAVASCRIPT

 angular.module('app', ['ui.router']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('state1', { url: ':city/events/:id', templateUrl: 'partials/events.html', controller: 'EventsController' }) .state('state2', { url: ':abc/cities/:x/:y', templateUrl: 'partials/cities.html', controller: 'CitiesController' }); }) .controller('EventsController', function($scope, $stateParams) { angular.extend($scope, $stateParams); }) .controller('CitiesController', function($scope, $stateParams) { angular.extend($scope, $stateParams); }); 
+3
source

Source: https://habr.com/ru/post/1201416/


All Articles