angular directive $formatters and $parsers

Using parsers and formatters for accepting phone numbers

by kshep92

HTML

<div ng-app="myApp" ng-controller="myCtrl">
    <input ng-model="data" type="text" test />
    {{data}}
</div>

JavaScript

angular.module('myApp', [])
.controller('myCtrl', function($scope){
   $scope.data; 
})
.directive('test', function(){
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel){
            /*ngModel.$formatters.push(function(value){
                //formats the value for display when ng-model is changed
                return value+' <- this'; 
            });*/
            ngModel.$parsers.push(function(value){
                //formats the value for ng-model when input value is changed
                if(value != undefined) return value.replace(/\D/g, '');
                else return value;
            });
        }
    };
});