LoginSignup
6
7

More than 5 years have passed since last update.

【AngularJS】テキストフォームの任意の位置にテキストを挿入するボタン

Last updated at Posted at 2015-03-27

ブログのリッチエディタなどによくある、テキストフォームの任意の位置にテキスト(リンクタグなど)を挿入するボタンをAngualrJSで実装する方法です。

利用ライブラリ

こちらを利用しています。
angular-caret

input(type="text")の場合

<input type="text" ng-model="textHoge" eb-caret="caretHoge">
<button ng-click="addHoge()">hoge</button>
$scope.textHoge = 'Lorem Ipsum'

$scope.addHoge = ->
  caret =  $scope.caretHoge.get
  text = $scope.textHoge
  if caret
    former = text.slice(0,caret)
    latter = text.slice(caret)
    $scope.textHoge = former + 'hoge' + latter
  else
    $scope.textHoge += 'hoge'
  return

textareaの場合

<textarea ng-model="textFuga" eb-caret="caretFuga"></textarea>
<button ng-click="addFuga()">fuga</button>
$scope.textFuga = 'Lorem Ipsum'

$scope.addFuga = ->
  caret =  $scope.caretFuga.get
  text = $scope.textFuga
  if caret
    former = text.slice(0,caret)
    latter = text.slice(caret)
    $scope.textFuga = former + '\n' + 'hoge' + '\n' + latter
  else
    $scope.textFuga += '\n' + 'hoge'
  return

実際のコードはこちら

簡単な解説

input(type="text)あるいはtextareaeb-caretを設定し、それをコントローラー側で.getとすることで、キャレット(カーソルの位置)を取得できるようです。

あとは、それを使って、バインドしているテキストの指定の位置に入れたいテキストを追加するだけですね。

eb.caretモジュールを依存性注入することを忘れないようにしてくだい。

angular
  .module 'app',['eb.caret']
  .controller 'appCtrl',appCtrl
6
7
1

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
6
7