特定标签的角度ui-mask

时间:2016-09-08 08:19:18

标签: javascript angularjs formatting mask phone-number

我有ui-mask="(999) 999-9999"的电话号码输入,现在我需要使用<span>{{phoneData}}中呈现电话数据。有没有办法在另一个html标签中使用ui-mask,而不仅仅是在输入中,以显示不错的手机数据?不是1234567890而是(123)456-7890

1 个答案:

答案 0 :(得分:0)

有一个非常简单的角度解决方案,没有任何遮罩,但有过滤器模块:{{phoneData | tel}}

.filter('tel', function () {
    return function (tel, params) {
        if (!tel) { return ''; }
        var options = params || {};

        var plus = tel.toString().trim()[0] === '+' ? '+' : '';

        var value = tel.toString().trim().replace(/^\+/, '').replace(/\-/g,'');

        if (value.match(/[^0-9]/)) {
            return tel;
        }

        var country, city, number;

        switch (value.length) {
            case 10: // +1PPP####### -> C (PPP) ###-####
                country = 1;
                city = value.slice(0, 3);
                number = value.slice(3);
                break;

            case 11: // +CPPP####### -> CCC (PP) ###-####
                country = value[0];
                city = value.slice(1, 4);
                number = value.slice(4);
                break;

            case 12: // +CCCPP####### -> CCC (PP) ###-####
                country = value.slice(0, 3);
                city = value.slice(3, 5);
                number = value.slice(5);
                break;

            default:
                country = "";
                city = value.slice(0, 3);
                number = value.slice(3);
                break;
        }

        if (country === 1 || options.country === false) {
            country = "";
            plus = "";
        }

        if(number){
            if(number.length>3){
                number = number.slice(0, 3) + '-' + number.slice(3);
            }
            else{
                number = number;
            }

            return (plus + country + " (" + city + ") " + number).trim();
        }
        else{
            return (plus + country + " (" + city).trim();
        }
    };
})