Ng-submit with textarea

时间:2015-07-17 13:41:16

标签: angularjs

我的表单只有一个文本区域。当用户在textarea中输入时,是否可以执行ng-submit?我能够使用ng-keyup完成此任务,但想知道是否有更好的解决方案。

<form ng-show="messages.conversation" ng-submit="messages.reply()">
  <textarea class="msg-textarea" ng-model="messages.replyText" 
            ng-keyup="$event.keyCode == 13 ? messages.reply() : null">
  </textarea>
  <button type="submit" value="submit" class="btn-primary btn-sm btn-block" 
          ng-click="messages.reply()">Reply
  </button>
</form>

1 个答案:

答案 0 :(得分:1)

@EpokK用以下代码解决了问题: How to use a keypress event in AngularJS?

您需要添加directive,如下所示:

<强>的Javascript

app.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if(event.which === 13) {
                scope.$apply(function (){
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

<强> HTML

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" ng-enter="doSomething()">    
</div>