Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

ブログのリッチエディタなどによくある、テキストフォームの任意の位置にテキスト(リンクタグなど)を挿入するボタンを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

実際のコードはこちら

http://plnkr.co/edit/i5Jqof2IBi5HZDqfZSNa?p=preview

簡単な解説

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

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

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

angular
  .module 'app',['eb.caret']
  .controller 'appCtrl',appCtrl
migi
フリーランス グロースデザイナー/フロントエンドエンジニア
http://migi.tech
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした