如何使用AngularJS UI路由器.go()将搜索参数添加到URL?

kal*_*hua 34 javascript angularjs angular-ui-router

有没有办法在使用UI-Router时向URL添加搜索参数$state.go()?我想在URL中使用带有附加信息的已定义状态,而不是使用相同的配置定义新路由.

我有一个简单的视图定义:

.when('page-with-form', {
    template: 'views/page-with-form.html',
    url: '/page-with-form'
})
Run Code Online (Sandbox Code Playgroud)

我希望当有人导航时路由正常工作,/page-with-form但是当我在应用程序中有其他东西时会将用户重定向到该路由,并带有一些/page-with-form?error=true类似这样的附加信息:

$state.go('page-with-form', '?error=true');
Run Code Online (Sandbox Code Playgroud)

Rad*_*ler 46

这将是解决方案ui-router- 工作示例

  $stateProvider
    .state('MyState', {
      url: '/page-with-form?error',
      templateUrl: 'view.page-with-form.html',
      controller: 'MyCtrl',
    })
Run Code Online (Sandbox Code Playgroud)

导航到此状态可能是这样的:

  // href
  <a href="#/page-with-form">
  <a href="#/page-with-form?error=true">
  <a href="#/page-with-form?error=false">

  //ui-sref
  <a ui-sref="MyState({error:null})">
  <a ui-sref="MyState({error:true})">
  <a ui-sref="MyState({error:false})">

  // state.go() - in fact very similar to ui-sref directive
  $state.go('MyState', {error: null})
  $state.go('MyState', {error: true})
  $state.go('MyState', {error:false})
Run Code Online (Sandbox Code Playgroud)

url params的文档:

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

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

这里测试它


Kha*_* TO 6

据我了解,您正在寻找可选的查询参数.幸运的是,默认情况下,查询参数是可选的.试一试:url: '/page-with-form?error'

.when('page-with-form', {
    template: 'views/page-with-form.html',
    url: '/page-with-form?error'
});
Run Code Online (Sandbox Code Playgroud)

并使用 $state.go('page-with-form', {error:true});