Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"optional" params in AngularJS states/views with ui-router

I have a customer search view that, by default, simply loads a form for first and last name. It can, however, take those params as arguments in the URL. My app config contains:

    $stateProvider         .state({             name:        "search",             url:         "/search",             templateUrl: "partials/customerSearch.html",             controller:  "CustomerSearchCtrl"         })         .state({             name:        "searchGiven",             url:         "/search/:fn/:ln",             templateUrl: "partials/customerSearch.html",             controller:  "CustomerSearchCtrl"         }) 

This works, but it seems like it has unnecessary redundancies. Is there a better way? Is this something $urlRouterProvider should handle?

like image 592
nshew13 Avatar asked Feb 24 '14 01:02

nshew13


People also ask

What is state params AngularJS?

What Is the $stateParams Service in Angular? $stateParams is a service that captures URL-based parameters, and we can use these parameters to display information according to the state. Let's create an example with two states, understand how states work, and use $stateparams to store parameters.

What is UI Router in AngularJS?

Angular-UI-Router is an AngularJS module used to create routes for AngularJS applications. Routes are an important part of Single-Page-Applications (SPAs) as well as regular applications and Angular-UI-Router provides easy creation and usage of routes in AngularJS.

What is UI-sref active in AngularJS?

ui-sref-active can live on the same element as ui-sref / ui-state , or it can be on a parent element. If a ui-sref-active is a parent to more than one ui-sref / ui-state , it will apply the CSS class when any of the links are active.

Is a optional parameter in URL?

Parameters provide a way of passing arbitrary data to a page via the URL. Optional parameters allow URLs to matched to routes even if no parameter value is passed. Things can get a bit complicated if you want to permit multiple optional parameters.


2 Answers

There's an issue in ui-router tracker about optional parameters. As of now, you can not specify them in clear way, but you can use regular expressions:

url: '/search{fn:(?:/[^/]+)?}' 

or query parameters:

url: '/search?fn&ln' 

People are working on it, though, so I'd expect desired functionality to land sometime in the future.

like image 100
Klaster_1 Avatar answered Sep 19 '22 05:09

Klaster_1


You can use:

$stateProvider .state({     name:        "searchGiven",     url:         "/search/{fn}/{ln}",     params: {         fn: {value: 'foo'},         ln: {value: 'bar'}     },     templateUrl: "partials/customerSearch.html",     controller:  "CustomerSearchCtrl" }) 
like image 38
user435943 Avatar answered Sep 22 '22 05:09

user435943