AngularJS custom directive
Problem Statement
- Create an angular directive to accept mobile number and country code
- Maximum of 10 digits should be allowed in mobile number
- Maximum of 4 digits should be allowed in country code
- Display appropriate message for validation
DEMO : AngularJS Phone number directive
Sorce code
<html>
<head>
<script src="jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="angular.min.js" type="text/javascript"></script>
</head>
<body>
<div ng-app="MyApp">
<div ng-controller="MyCntrl">
<hr />
{{name}}
<div my-directive="">
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var app = angular.module("MyApp", []);
app.controller("MyCntrl", function ($scope) {
$scope.name = "AngularJS Phone number directive demo";
});
app.directive("myDirective", function () {
return {
restrict: "A",
template: '<ng-form name="MyForm" ><input ng-pattern="/^[0-9]*$/" name="CountryCode" ng-model="CountryCode" placeholder="Country Code" maxlength="4" /> ' +
'<input ng-pattern="/^[0-9]*$/" placeholder="Phone number" name="PhoneNumber" ng-model="PhoneNumber" maxlength="10" />' +
'<b>    Phone Number is : {{ CompleteNumber = "+" + CountryCode + PhoneNumber}}{{}}</b>' +
'</br><span ng-if="MyForm.PhoneNumber.$invalid">Please enter valid phone number</br></span>' +
'<span ng-if="MyForm.CountryCode.$invalid">Please enter valid Country Code</span>' +
'</ng-form>'
};
});
</script>
No comments