JSFiddle - React, Tailwind, and code Playground
HTML
<form name="myform" ng-controller="myFormController" novalidate>
Directive:<br />
<email-input ng-model="registration.email"
name="email"
label="E-mailadres"></email-input>
<br />Normal input:<br />
<input type="email" name="emailnormal" ng-model="registration.email" required/>
<span class="f-error" ng-show="myform.emailnormal.$error.required">Required</span>
<span class="f-error" ng-show="myform.emailnormal.$error.email">Wrong format</span>
<br />
<br />
Output: {{registration.email}}
</form>
CSS
.f-error { color:red; }
JavaScript
; (function () {
var templateInput = '<div><input type="email" name="{{name}}" id="reg-{{name}}" ng-model="model" required/>'
+ '<span ng-show="errorRequired()">Required</span>'
+ '<span ng-show="errorEmail()">Wrong format</span></div>';
//main angular module
angular.module('formTest', [])
.controller("myFormController", ['$scope', function ($scope) {
//register model
$scope.registration = {
email: null
};
}])
.directive("emailInput", [function () {
return {
restrict: "E",
replace: true,
template: templateInput,
require: 'ngModel',
scope: {
model: '=ngModel',
name: '@name',
label: '@label'
},
link: function (scope, element, attrs, ngModel) {
scope.errorRequired = function () {
return ngModel.$error.required;
};
scope.errorEmail = function () {
console.log(ngModel); //<- ngModel is not in sync or linked to the model I require to validate
return ngModel.$error.email; //<- keeps returning undefined
};
}
}
}])
;
})();