简体   繁体   English

使用angularjs的电话格式的自定义指令

[英]Custom directive for telephone format using angularjs

I am trying to write custom directive for USA telephone number using angularjs and need to preserve the data type of the field as integer.Here is the jsfiddle directive and need help to complete the directive. 我正在尝试使用angularjs为美国电话号码编写自定义指令,并且需要将字段的数据类型保留为整数。这是jsfiddle 指令 ,需要帮助来完成该指令。

If user enters a valid telephone no (exactly 10 numbers ie.1234567890) then input should split into 3 chunks as 123-456-7890 when the user moves to next control.otherewise I should show error message "not a valid number". 如果用户输入有效的电话号码(恰好10个号码,即1234567890),则当用户移至下一个控件时,输入应分为3个块,分别为123-456-7890。否则,我应该显示错误消息“无效的号码”。

<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
    <input type="text" ng-model="telephone" phoneformat  name="input1" />
     <span class="error" ng-show="myForm.input1.$error.telephone">Numbers only!</span>
    <span class="error" ng-show="myForm.input1.$error.telephone">Exact 10 Numbers only!</span>

</form>
</div>

var myApp = angular.module("myApp", []);

var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);

 myApp.directive("phoneformat", function () {
  return {
    restrict: "A",
    require: "ngModel",
    link: function (scope, element, attr, ngModelCtrl) {
        var phoneformat = function () {

        }

      }
    };
 });

您可能要使用http://angular-ui.github.io/ui-utils/ Mask指令。

Working Fiddle: http://jsfiddle.net/HB7LU/6581/ 工作小提琴: http//jsfiddle.net/HB7LU/6581/

myApp.directive("phoneFormat", function () {

return {
    restrict: "A",
    link: function (scope, element, attr) {

        element.bind('change', function() {
            if ( this.value.length === 10 ) {
               var number = this.value;
               this.value = number.substring(0,3) + '-' + number.substring(3,6) + '-' + number.substring(6,10)
            }
            else {
                document.querySelector('.helpblock').innerHTML = 'error in formatting';
            }
        });

    }
};

}); });

Iv'e extended your original fiddle. 我扩大了你原来的小提琴。 here's the result: http://jsfiddle.net/10k58awt/ 结果如下: http : //jsfiddle.net/10k58awt/

You can find splittedNumber array (contains 3 parts of number) on form submission 您可以在表单提交时找到splittedNumber数组(包含数字的3个部分)

js: JS:

var myApp = angular.module("myApp", []);

var myCtrl = myApp.controller("myCtrl", ["$scope", function ($scope) {
    $scope.telephone = "1234567890";
    $scope.submit = function () {

        var splittedNumber = [$scope.telephone.substring(0, 3), $scope.telephone.substring(3, 6), $scope.telephone.substring(6, 10)];

        // Do something with splitted number
        console.log(splittedNumber);
    };
}]);

myApp.directive("phoneformat", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (phoneInput) {
                phoneInput = phoneInput.trim();
                if (phoneInput && phoneInput.length == 10 && !isNaN(phoneInput)) {
                    ctrl.$setValidity('phoneformat', true);
                    return phoneInput;
                } else {
                    ctrl.$setValidity('phoneformat', false);
                    return undefined;

                }
            });
        }
    };
});

html: HTML:

<div ng-app="myApp" ng-controller="myCtrl">
    <form name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        <input type="text" ng-model="telephone" phoneformat name="input1" /> <span class="error" ng-show="myForm.input1.$error.phoneformat">Invalid US Phone number!</span>

        <div>
            <button class="btn btn-primary" type="submit" ng-class="{'disabled': !myForm.$valid}">submit</button>
        </div>
    </form>
</div>

It looks like you want to leverage the $error property of the form to drive validation. 看来您想利用表单的$ error属性来驱动验证。 To do this, you will need to call $setValidity in the ngModelCtrl that you have required into your directive: 为此,您需要在指令中需要的ngModelCtrl中调用$ setValidity:

var myApp = angular.module("myApp", []);

var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
    $scope.telephone = "1234567890";
}]);

myApp.directive("phoneformat", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attr, ngModelCtrl) {
            //Parsing is performed from angular from view to model (e.g. update input box)
            //Sounds like you just want the number without the hyphens, so take them out with replace
            var phoneParse = function (value) {
                var numbers = value && value.replace(/-/g, "");
                if (/^\d{10}$/.test(numbers)) {
                    return numbers;
                }

                return undefined;
            }
            //Formatting is done from view to model (e.g. when you set $scope.telephone)
            //Function to insert hyphens if 10 digits were entered.
            var phoneFormat = function (value) {
                var numbers = value && value.replace(/-/g,"");
                var matches = numbers && numbers.match(/^(\d{3})(\d{3})(\d{4})$/);

                if (matches) {
                    return matches[1] + "-" + matches[2] + "-" + matches[3];
                }

                return undefined;
            }

           //Add these functions to the formatter and parser pipelines
           ngModelCtrl.$parsers.push(phoneParse);
           ngModelCtrl.$formatters.push(phoneFormat);

           //Since you want to update the error message on blur, call $setValidity on blur
           element.bind("blur", function () {
                var value = phoneFormat(element.val());
                var isValid = !!value;
                if (isValid) {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                }

                ngModelCtrl.$setValidity("telephone", isValid);
                //call scope.$apply() since blur event happens "outside of angular"
                scope.$apply();
            });
        }
    };
});

Working fiddle . 工作提琴 This was just a quick way of demonstrating the parser and formatter pipelines that are used in ngModel, along with $setValidity -- which is used to populate the $error field(s). 这只是演示ngModel中使用的解析器和格式化程序管道以及$ setValidity的快速方法,后者用于填充$ error字段。

Update: To use this same phone validation across multiple phones, use form with $error. 更新:要在多部电话中使用同一电话验证,请使用带有$ error的表格。 Notice that each input gets a unique name that is used with myForm (name of form). 请注意,每个输入都有一个与myForm一起使用的唯一名称(表单名称)。 Both use $error.telephone: 两者都使用$ error.telephone:

<form name="myForm">
    Mobile Phone:
    <input type="text" ng-model="mobilephone" phoneformat name="mobilephone" />
    <span class="error" ng-show="myForm.mobilephone.$error.telephone">
       Exact 10 Numbers only!
    </span>
    <br />
    Home Phone:
    <input type="text" ng-model="homephone" phoneformat  name="homephone" />
    <span class="error" ng-show="myForm.homephone.$error.telephone">
        Exact 10 Numbers only!
    </span>
</form>

Updated fiddle . 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM