21
20

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でngModelをinputに付けたときに日本語入力がリアルタイムで反映されない問題

Last updated at Posted at 2014-05-09
<input ng-model="hoge" type="text">
<h1>{{hoge}}</h1>

上みたいにソースを書き,実際にテキスト入力をするとき,日本語入力を確定しないとmodelに反映されない問題がある.
angularjsの1.2.7以上のバージョンで確認できる.
Angularjs公式の最初のサンプルでも確認することができる.
Win8.1+MicrosoftIME環境,ブラウザはIE,Firefox,Chromeで確認.

とりあえず以下の用なdirectiveを作成してngModelの代わりに使うと回避できる.

app.directive('jpNgModel', function($parse){
    return {
        restrict:'A',
        link:function(scope, element, attrs){
            var getter = $parse(attrs.jpNgModel);
            var setter = getter.assign;
            var value = getter(scope);
            element.bind('input', function(){
                setter(scope, element.val());
                scope.$apply();
            });
            
            scope.$watch(attrs.jpNgModel, function(n){
                if(n !== element.val()){
                    element.val(n);
                }
            });
        }
    }
});

使用例

<input jp-ng-model="hoge" type="text">
<h1>{{hoge}}</h1>
21
20
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
21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?