[AngularJS] 半角から全角に変換する Directive
by yuta takuman
HTML
<div ng-app="myApp" ng-controller="SampleCtrl">
<label>input (ng-model有)</label></br>
<input type="text" ng-model="hoge" style="width:200px" convert-ascii-to-mb />
</br>
</br>
<label>input (ng-model無)</label></br>
<input type="text" style="width:200px" convert-ascii-to-mb />
</br>
</br>
<label>textarea (ng-model有)</label></br>
<textarea ng-model="hoge_text" style="width:200px" convert-ascii-to-mb>
</textarea>
</br>
</br>
<label>textarea (ng-model無)</label></br>
<textarea style="width:200px" convert-ascii-to-mb>
</textarea>
</div>
JavaScript
var myApp = angular.module('myApp', []);
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) {
for (var i = 0; i < s.length; i++) {
return String.fromCharCode(s.charCodeAt(i) + 0xFEE0);
}
});
if (ngModel !== null) {
scope.$apply(function () {
ngModel.$setViewValue(word);
});
}
this.value = word;
});
}
};
});
myApp.controller('SampleCtrl', ['$scope', function ($scope) {
$scope.hoge = "";
$scope.hoge_text = "";
}]);