Validation errors are handled by FormController so it's reasonable to keep all validation-related data inside the form object itself. This could be implemented by attaching arbitrary data to myform
instance:
app.factory('myServer', function(){
return {
getConflict: function(viewValue){
var comparedAgainst = 'existing@email.com';
if(viewValue === comparedAgainst){
return comparedAgainst;
}
}
}
});
app
.directive('conflictcheck', function (myServer) {
return {
require: ['ngModel', '^form'],
link: function (scope, elm, attrs, ctrls) {
var ngModelCtrl = ctrls[0];
var ngFormCtrl = ctrls[1];
ngModelCtrl.$parsers.unshift(function (viewValue) {
// getConflict returns conflicting value
var conflict = myServer.getConflict(viewValue);
if (!conflict) {
ngModelCtrl.$setValidity('conflictcheck', true);
return viewValue;
} else {
ngModelCtrl.$setValidity('conflictcheck', false);
// We attach validation-specific data to arbitrary data property
ngFormCtrl.foo.data = {
conflictcheck: conflict
};
return undefined;
}
});
}
};
});
<form name="myform" novalidate>
Email:
<input ng-model="foo" name="foo" conflictcheck />
<div ng-show="myform.foo.$error.conflictcheck">
Error: Foo conflicts with {{myform.foo.data.conflictcheck}}!
</div>
</form>