8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJS で focus を設定する directive 作った

Posted at

入力フォームの値に変更があったときに focus する directive を作ってみました。

Gist: https://gist.githubusercontent.com/onjiro/0295ac5a1f51da101806/raw/78f3d246c8b023a1285486f746d65d91c40b4f08/ng_focus_on_change.js

ユーザーによる入力フォームの値の変更、スクリプト中での値の変更の両方で発火します。
次のようなパターンでの3の挙動を実現する際に利用できるかと思います。

  1. 入力フォームを submit
  • 入力フォームをリセット
  • 入力フォームの先頭にフォーカスを移動
ng_focus_on_change.js
angular.module('ngFocusOnChange', [])
  .directive('ngFocusOnChange', ['$timeout', function($timeout) {
    return {
      link: function(scope, element, attrs) {
        scope.$watch(attrs.ngFocusOnChange, function(newValue, oldValue) {
          // 以下のエラーを避けるために $timeout を使用
          // watch の最中に DOM イベントを発生させてはいけない
          // "Error: [$rootScope: inprog]"
          // https://docs.angularjs.org/error/$rootScope/inprog?p0=$digest
          if (newValue !== oldValue) {
            $timeout(function() { element.focus(); });
          }
        });
      }
    };
  }]);
usage_example.html
<input name="date"
       type="date"
       ng-model="anyValue"
       ng-focus-on-change="anyValue" />

こういう directive 誰かがもう作ってると思うのだけど、どこかに落ちてないものかしら。。。

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?