LoginSignup
2
1

More than 5 years have passed since last update.

AngularJS で半角から全角に変換する Directive を追加する

Last updated at Posted at 2015-05-23

AngularJS で全角から半角に変換する Directive を追加する の逆バージョンです。
JavaScript で Form の value に半角で入力された値を全角へ変換する関数を、AngularJS の Directive に書き換えてみた

JavaScript バージョン

inputタグ
<input name="phone" type="text" placeholder="09012345678" onchange="han2zen(this)">
zen2han.js
function han2zen(obj){
  // 文字列かチェック
  if(typeof(obj.value)!="string") return false;
  var word = obj.value;

  obj.value = word.replace(/[!"#$%&'()*+,\-.\/0-9:;<=>?@A-Z\[\\\]^_`a-z{|}~]/g, function(s) {
      return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);    
  })
}

デモ

AngularJS Directive バージョン

inputタグ(ng-model無)
<input name="phone" type="text" placeholder="09012345678" convert-ascii-to-mb >
inputタグ(ng-model有)
<input name="phone" type="text" placeholder="09012345678" ng-model="phone" convert-ascii-to-mb >
app.js
angular
    .module('MyApp', [])
    // 英数字記号の半角文字を全角へ変換
    .directive('convertAsciiToMb', function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            link: function (scope, element, attrs, ngModel) {
                element.on('change', function(){
                    if(typeof(this.value)!="string") return false;
                    var word = this.value;
                    word = word.replace(/[!"#$%&'()*+,\-.\/0-9:;<=>?@A-Z\[\\\]^_`a-z{|}~]/g, function(s) {
                        return String.fromCharCode(s.charCodeAt(0) + 0xFEE0);    
                    });
                    // ng-model への反映(これがないとフォームの値だけ更新され、ng-modelの値は更新されない)
                    if (ngModel != null) {
                        scope.$apply(function() {
                            ngModel.$setViewValue(word);
                        });
                    }
                    this.value = word;
                });
            }
        };
    })

デモ

参考
AngularJS で全角から半角に変換する Directive を追加する

2
1
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
2
1