In a custom validation directive I ensure that the entered value does not conflict with others in the database. If it does, I would like to tell the user not only that there's a conflict, but also the name of the item it is conflicting with.
Storing these details in the scope would probably work, but doesn't seem right to me at all. Is there a better way?
Directive:
angular.module('myApp')
.directive('conflictcheck', function (myServer) {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
var conflict = myServer.getConflict(viewValue);
if (!conflict) {
ctrl.$setValidity('conflictcheck', true);
return viewValue;
} else {
ctrl.$setValidity('conflictcheck', false);
// pass additional info regarding the conflict here
return undefined;
}
});
}
};
});
View:
<form name="myform" action="#">
<input ng-model="foo" conflictcheck />
<div ng-if="myform.foo.$error.conflictcheck">
Error: Foo conflicts with XXXXXXXX!
</div>
</form>