在表单提交时使用 URL 发送路由参数

Sending routeparams with the URL on form submit

本文关键字:路由 参数 URL 表单提交      更新时间:2023-09-26

当用户单击提交按钮时,我需要发送带有URL的路由参数。

这是我的简单表格

<form action="#/chat/{{username}}">
    <input type="text" placeholder="enter a username..." ng-model="username" required  autofocus><br/>
    <input type="submit" value="submit">
  </form>

但这不起作用,因为"用户名"变量没有绑定,而是转到/chat/%7B%7Busername%7D%7D(有人启发我为什么会发生这种情况)

目前,我遵循的解决方法是使用超链接而不是提交按钮

 <div>
    <input type="text"  class="form-control" placeholder="enter a username..." ng-model="username" required  autofocus><br/>
    <a href="#/chat/{{username}}" class="btn btn-lg btn-primary btn-block"  >Start Chatting</a>
  </div>

但是上述方法的问题在于,当用户按ENTER键时它不起作用(因为它不是提交按钮)

那么实现这一目标的正确方法是什么?

标记:

<form ng-submit="onSubmit()">
  <input type="text" placeholder="enter a username..." ng-model="username" required  autofocus><br/>
  <button type="submit">submit</submit>
</form>

JavaScript 控制器:

app.controller('ctrl', function($location) {
  $scope.username = '';
  $scope.onSubmit = function() {
    $location.url('/chat/' + $scope.username);
  };
});

或类似的东西:)

HTML:

<form ng-submit="onSubmit()">
  <input type="text" placeholder="enter a username..." ng-model="username"  required  autofocus><br/>
  <button type="submit">submit</submit>
</form>

控制器:

app.controller('ctrl', function($state) {
  $scope.username = 'example name';
  $scope.onSubmit = function() {
    $state.go('/chat/' + $scope.username);
  };
});

文档:

角度用户界面

$state.go('$scope.username') - will go to the state according to user name
$state.go('^') - will go to a parent state
$state.go('^.sibling') - will go to a sibling state
$state.go('.child.grandchild') - will go to grandchild state

根据堆栈上的另一个帖子:

$location服务在开箱即用的 Angular.js 框架上,允许您管理位置对象(类似于纯 JavaScript)。$state服务是 ui-router 模块的一部分,允许您在高级模式下管理路由,贯穿状态机视图管理。

如果使用 ui-router,则最好使用$state服务来管理状态/路由,因为状态抽象了路由的概念,您可以在不更改状态的情况下更改物理路由。

堆栈帖子