LoginSignup
3
3

More than 5 years have passed since last update.

[Angular.js]Enterで入力確定させるtextarea用directive

Last updated at Posted at 2015-02-12

チャットサービスでよくある、Enterを押すと入力を確定させるtextareaをdirectiveで作ってみた。

directive

こんな感じ。

onEnter.js
app.directive('onEnter', function() {
  return {
    scope: {
      onEnter: "&"
    },
    link: function(scope, element, attrs) {
      angular.element(element[0]).on('keydown', function(e) {
        if (e.which == 13) {
          var text = angular.element(this).val();
          if (text) {
            scope.onEnter({text: text});
            angular.element(this).val('');
            e.preventDefault();
          }
        }
      });
    }
  }
});

使い方

機能を付与したいtexareaにon-enterをバインド。注意点として、呼び出す関数に渡す引数はtextとする(directive内でtextで渡しているので合わせる)。

index.html
<div ng-controller="MyController">
    <textarea on-enter="onEnter(text)"></textarea>
</div>

これでバインドしているControllerの関数を呼び出すことが出来る。

myController.js
app.controller('MyController', ['$scope', function($scope) {
  $scope.onEnter = function(text) {
    // ここに処理を書く
  }
}]);  
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3