0

I'm breaking my head over a small issue. I have a chat box in my web app which contains one input[type='text'] and a button. What I want is whenever user clicks on the button, the corresponding message is sent to server and clears the input field on button click.

I'm facing an issue where when a user types in input[type='text'], it causes my controller to refresh. Also, on clicking the button, the controller refreshes.

I have found few threads which mention similar problem but somehow the solution mentioned in these thread is not working for me.

AngularJS, clicking a button within a form causes page refresh

Following is my code:

<form name="form">
  <div class="input-group">
    <input type="text" name="message" placeholder="Type Message ..." ng-model="form.newMessage" class="form-control"/><span class="input-group-btn">
      <button type="button" ng-click="submitNewMessage()" class="btn btn-info btn-flat">Send</button></span>
  </div>
</form>

Can anyone please help with this?

Thanks

Update:

Based on the suggested solutions I modified my code. But it is still not wokring:

<form name="form" ng-submit="submitNewMessage()">
  <div class="input-group">
    <input type="text" name="message" placeholder="Type Message ..." ng-model="form.newMessage" class="form-control"/><span class="input-group-btn">
      <button type="submit" class="btn btn-info btn-flat">Send</button></span>
  </div>
</form>

Here is my controller code:

$scope.submitNewMessage = function(){
  event.preventDefault();
  console.log($scope.form.newMessage);

}

Also, my doubt is even on writing anything in the input box, it refreshes the page. Why is it so ? Shouldn't it wait till I submit the form ?

Update 2: It seems the actual problem is different from this. I have created a different question and this might solve this problem as well. Can anyone please tale a look at this? Thanks

Community
  • 1
  • 1
dark_shadow
  • 3,503
  • 11
  • 56
  • 81

2 Answers2

0

In order to avoid the submition of the form, you have to add an event.preventDefault() to your submitNewMessage function.

Other way is to remove the form tags.

graham o'donnel
  • 385
  • 2
  • 5
  • 18
0

To stop the page from reloading when you click the button, try this:

$scope.submitNewMessage = function($event) {
  event.preventDefault();
  // your code
$scope.form.newMessage = ''; // to empty your input afterwards
}