A directive to format phone number

后端 未结 7 1911
梦毁少年i
梦毁少年i 2021-01-02 00:33

I was wondering how to automatically format a number in an input field using an angularjs directive? When I type in an input field say 6042919283 I want it to be shown as 6

7条回答
  •  一整个雨季
    2021-01-02 01:24

    If your phone number is uniform i.e all the number is of digit 10 this one will work

      app.directive('formatPhone', [
            function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, elem, attrs, ctrl, ngModel) {
                        elem.add(phonenumber).on('keyup', function() {
                           var origVal = elem.val().replace(/[^\w\s]/gi, '');
                           if(origVal.length === 10) {
                             var str = origVal.replace(/(.{3})/g,"$1-");
                             var phone = str.slice(0, -2) + str.slice(-1);
                             jQuery("#phonenumber").val(phone);
                           }
    
                        });
                    }
                };
            }
        ]);
    

    And your html;

    
    

提交回复
热议问题