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

Per*_*son 61 javascript query-parameters angularjs angular-ui angular-ui-router

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

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

($ location.search()).UID

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

thi*_*eek 99

请参阅URL路由文档的查询参数部分.

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

url: "/contacts?myParam"
// will match to url of "/contacts?myParam=value"
Run Code Online (Sandbox Code Playgroud)

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

{ myParam: 'value' }
Run Code Online (Sandbox Code Playgroud)

  • 对于查询参数,您必须使用`$ state.params`,因为它写在答案中.不是`$ stateParams`我用过但没用过. (11认同)
  • @thisgeek当我使用url:"/ verifyMail?username"我得到$ state.params空值 (4认同)

Nat*_*ele 55

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

编辑:的文档,如果你想捕捉的查询参数$stateParams,就可以追加?到你url,并命名每个查询参数,通过分离&,即url: "/foo?bar&baz".


SSt*_*ley 9

ui-router不像$ location服务那样区分URL中的不同类型的参数.

在您的控制器中,您可以使用$ stateParams服务来访问您网址中所有不同类型的参数.

下面是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' }
Run Code Online (Sandbox Code Playgroud)

所以在你的情况下找到uid param只需使用:

$scope.uid = $stateParams.uid
Run Code Online (Sandbox Code Playgroud)


fre*_*tma 7

您还需要在$ 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;
  }
})
Run Code Online (Sandbox Code Playgroud)

benfoster.io解释