<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app='myApp' ng-controller='myController'>
<label>Format: </label>
<input type='text' ng-model='inputFormat' />
<input type="button" value="Submit" ng-click="setFormat()" />
<div>
<samp>
<br/>
<label>Example:</label>
<ul>
<li>(___) ___ ____</li>
<li>(___)-___-___</li>
<li>___-___-____</li>
</ul>
</samp>
</div>
<div>
<hr/>
<strong ng-if='format'>Number format set to: {{format}}</strong>
<strong ng-if='!format'>Please set the number format.</strong>
</div>
<br/>
<label> Mobile #: </label>
<input type='text' srik-net-number format='{{format}}' ng-model="inputText" />
</body>
</html>
// Code goes here
var myApp = angular.module('myApp', []);
myApp.controller('myController', ['$scope', function($scope) {
$scope.setFormat = function() {
$scope.format = $scope.inputFormat;
$scope.inputText='';
}
}]);
myApp.filter('numberFormat', function() {
return function(format, input) {
var lastChar;
format=format||'(___)-___-____';
if (!input) {
return;
}
for (var index = 0; index < input.length; index++) {
var char = input.charAt(index);
if (parseInt(char)) {
if (format.indexOf('_') >= 0) {
format = format.replace('_', char);
lastChar = char;
}
}
}
if (lastChar) {
return format.substring(0, format.lastIndexOf(lastChar) + 1);
}
}
});
myApp.directive('srikNetNumber', ['$filter', function($filter) {
return {
resolve: 'A',
replace: true,
link: function(scope, ele, attrs) {
var modelName = attrs.ngModel;
scope.$watch(modelName, function(newValue, oldValue) {
var formatValue = attrs.format;
scope[modelName] = $filter('numberFormat')(formatValue, newValue);
});
}
}
}]);
/* Styles go here */