How to extract request parameters using ui-router for AngularJS?

How to extract request parameters using ui-router for AngularJS?

In AngularJS's own $location service, I did:

($ location.search ()). UID

to extract the uid parameter from the url. What is the appropriate code for ui-router?

+58
javascript angularjs angular-ui-router angular-ui query-parameters
Sep 27 '13 at 15:00
source share
6 answers

If you do not bind to the request parameters (see the documentation), you do not directly access them through $state or $stateParams . Use the $location service.

EDIT: In documents , if you want to capture request parameters in $stateParams , can you add a ? to your url and name each request parameter separated by & , that is url: "/foo?bar&baz" .

+51
Sep 27 '13 at 22:07
source share

See the query parameters section of the URL routing documentation .

You can also specify parameters as query parameters by following "?":

 url: "/contacts?myParam" // will match to url of "/contacts?myParam=value" 

In this example, if url /contacts?myParam=value , then the value of $state.params will be:

 { myParam: 'value' } 
+93
Nov 23 '13 at 16:58
source share

ui-router does not distinguish between different types of parameters in a URL, for example, in the $ location service.

In your controllers, you can use the $ stateParams service to access all of the various types of parameters in your URL.

The following is an example from the wi-router wiki:

 // Then you navigated your browser to: '/users/123/details/default/0?from=there&to=here' // Your $stateParams object would be { id:'123', type:'default', repeat:'0', from:'there', to:'here' } 

So, in your case, to search for the uid parameter just use:

 $scope.uid = $stateParams.uid 
+9
Dec 10 '15 at 1:13
source share

You also need to define the request parameters in $ stateProvider, for example:

 state('new-qs', { url: '/new?portfolioId&param1&param2', templateUrl: 'new.html', controller: function($scope, $stateParams) { $scope.portfolioId = $stateParams.portfolioId; $scope.param1 = $stateParams.param1; $scope.param2 = $stateParams.param2; } }) 

as benfoster.io explains

+6
Jan 07 '16 at 13:22
source share

You can get it from $ stateParams, but in this case you also need to declare a request variable on the route.

announce in the route how -

 url: '/path?name' 

to get the name in the controller, enter $ stateParams, and use as -

$stateParams.name

+2
May 23 '17 at 12:31
source share

For the latest versions of AngularJS and ui-router, I think you can just use $state to access the options:

 $state.params[<PARAMETER_NAME>] 

where in app.js you defined the state as follows:

 .state('app.name', { url: '/:some_param_id', templateUrl: '/templates/home.html' }) 
0
Jan 17 '19 at 16:06
source share



All Articles