Search code examples
javascripthtmlangularjsangularjs-routing

Sending routeparams with the URL on form submit


I need to send route params with the URL when the user clicks on submit button.

Here is my simple form

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

But this doesn't work as the 'username' variable doesn't bind and it goes to /chat/%7B%7Busername%7D%7D instead (somebody enlighten me on why this happens)

Currently, the workaround I am following is using a hyperlink instead of a submit button

 <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>

But the problem with the above approach is that it doesn't work when the user presses ENTER key (as it is not the submit button)

So what is the correct way to achieve this?


Solution

  • Markup:

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

    JavaScript Controller:

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

    Or something like that :)