<!DOCTYPE html>
<html ng-app="validationApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.6" src="//code.angularjs.org/1.2.6/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
  <div class="container" ng-controller="ValidationController as validationController">
  	<form name="myForm">
  		{{employee | json}}
    <custom-input ng-required="true" ng-model="employee.name" name="employee.name" id="employeeName" ng-pattern="/^[0-9]{1,7}$/"></custom-input>
    <span ng-show="myForm['employee.name'].$error.pattern">This is a invalid field</span>
    <span ng-show="myForm['employee.name'].$error.required">This is a required field</span>
	</form>
  </div>
  <script type="text/ng-template" id="/templates/customInput.html">
  	<div>
  		<input type="text" name="{{name}}" ng-model="newInput" id="{{id}}">
  	</div>
  </script>
  </body>

</html>
angular.module('validationApp', [])
.controller("ValidationController", function(){

})
.directive("customInput", function(){
	return {
		restrict: "E",
		require : "ngModel",
		replace: "true",
		templateUrl : "/templates/customInput.html",
		scope : {
			id : "@", //bind id to scope
			name : "@" //bind name to scope
		},
		link: function(scope, element, attrs, ngModelCtrl){
			//When newInput is updated, update the model of original input
			 scope.$watch('newInput', function(newValue){
                ngModelCtrl.$setViewValue(newValue);
            });

			//On first load, get the initial value of original input's model and assign it to new input's model
            ngModelCtrl.$render = function(){
                var viewValue = ngModelCtrl.$viewValue;
                if(viewValue){
                    scope.newInput = viewValue;
                }
            }
		}
	}
});

/* Styles go here */