在表单提交时发送带有 URL 的路由参数

Sending routeparams with the URL on form submit

当用户点击提交按钮时,我需要使用 URL 发送路由参数。

这是我的简单表格

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

但这不起作用,因为 'username' 变量没有绑定,而是转到 /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);
  };
});

文档:

Angular Ui

$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

每个 post 在堆栈上:

the $location service is on the angular.js framework out of the box and allow you to manage location object (similar in pure javascript). The $state service is part of ui-router module and allow you to manage routes in an advanced mode, throughout a state machine management of views.

如果你使用 ui-router,你应该更喜欢使用 $state 服务来管理 states/routes 因为状态抽象了路由的概念,你可以在不改变状态的情况下改变物理路由。

Stack Post