如何使用ui-router为AngularJS提取查询参数?

时间:2013-09-27 15:00:57

标签: javascript angularjs angular-ui query-parameters angular-ui-router

如何使用ui-router为AngularJS提取查询参数?

在AngularJS自己的$location服务中我做了:

  

($ location.search())。UID

从URL中提取参数uid。 ui-router的相应代码是什么?

6 个答案:

答案 0 :(得分:98)

请参阅URL routing documentation的查询参数部分。

  

您还可以在'?'后面指定参数作为查询参数:

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

对于此示例,如果网址为/contacts?myParam=value,则$state.params的值为:

{ myParam: 'value' }

答案 1 :(得分:54)

除非您绑定查询参数(请参阅文档),否则不会通过$state$stateParams直接访问它们。使用$location服务。

编辑:根据the docs,如果您想在$stateParams中捕获查询参数,可以在?附加url,并命名每个查询参数,以&分隔,即url: "/foo?bar&baz"

答案 2 :(得分:9)

ui-router does not differentiate between different types of parameters in a url like the $location service does.

In your controllers you can use the $stateParams service to get access to all the different types of parameters in your url.

below is an example from the ui-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 find the uid param simply use:

$scope.uid = $stateParams.uid

答案 3 :(得分:6)

您还需要在$ stateProvider中定义查询参数,例如

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;
  }
})

benfoster.io

解释

答案 4 :(得分:2)

您可以从$ stateParams获取它,但在这种情况下,您还必须在路由中声明查询变量。

在路线中声明 -

url: '/path?name'

获取控制器中的名称注入$ stateParams, 并使用像 -

$stateParams.name

答案 5 :(得分:0)

对于AngularJS和ui-router的最新版本,我认为您可以使用$state来访问参数:

$state.params[<PARAMETER_NAME>]

在app.js中,您将状态定义如下:

.state('app.name', {
    url: '/:some_param_id',
    templateUrl: '/templates/home.html'
})
相关问题