0

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?

2 Answers2

0

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

o4ohel
  • 1,779
  • 13
  • 12
0

HTML:

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

Controller:

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

Docs:

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

Per another post on stack:

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.

If you use ui-router, you should prefer to use $state service to manages states/routes because state abstracts the concept of route and you could change the phisical routes without changing states.

Stack Post

Community
  • 1
  • 1
alphapilgrim
  • 3,761
  • 8
  • 29
  • 58