LoginSignup
7
8

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-05-22

以前作った JavaScript で Form の value に全角で入力された値を半角へ変換する関数を、AngularJS の Directive に書き換えてみた

JavaScript バージョン

inputタグ
<input name="phone" type="text" placeholder="09012345678" onchange="zen2han(this)">
zen2han.js
function zen2han(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-mb-to-ascii >
inputタグ(ng-model有)
<input name="phone" type="text" placeholder="09012345678" ng-model="phone" convert-mb-to-ascii >
app.js
angular
    .module('MyApp', [])
    // 英数字記号の全角文字を半角へ変換
    .directive('convertMbToAscii', 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;
                });
            }
        };
    })

デモ

require を ngModel としてしまうと、下記のエラーが発生してしまうが、
必要ないので ?ngModel にして、発生しないようにしてます。
更に、同じタグに ng-model があった場合には、フォームの値だけでなく、ng-model の値も
更新するようにしてます。

Error: [$compile:ctreq] Controller 'ngModel', required by directive 'convertMbToAscii', can't be found!

参考
AngularJS Directive なんてこわくない(その4)

ついでに逆バージョンも用意してみました
AngularJS で半角から全角に変換する Directive を追加する

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