hiattp
hiattp

Reputation: 2336

AngularJS unexpectedly leaves line break in textarea

When a user presses return after typing in my textbox the content should be pushed to some other model and the textarea should clear:

HTML

<div ng-controller="MyCtrl">
  <ul><li ng-repeat="msg in messages">{{msg.body}}</li></ul>
  <textarea ng-model="msg" ng-keydown="addMessage($event)"></textarea>
</div>

JS

function MyCtrl($scope) {
  $scope.messages = [];
  $scope.addMessage = function(e) {
    if (e.keyCode != 13) return;
    $scope.messages.push({body: $scope.msg});
    $scope.msg = "";
  }
}

However, $scope.msg = "" leaves the line break so the next message starts on the second line of an otherwise empty textarea. How can I can I clear it entirely and start the next input on the first line? Here is a fiddle to demonstrate, and here is a non-angular related question.

Upvotes: 1

Views: 793

Answers (1)

Sacho
Sacho

Reputation: 2179

Once your event handler is executed(and you clear the textarea), the default event handling mechanism is triggered - which adds the newline from pressing enter. You should prevent the default in your handler(e.preventDefault()) : fiddle

Edit: It seems like the question was answered in the link you mentioned already.

Upvotes: 3

Related Questions