Skip to content

Instantly share code, notes, and snippets.

@jamie-pate
Created September 16, 2013 15:34
Show Gist options
  • Save jamie-pate/6582262 to your computer and use it in GitHub Desktop.
Save jamie-pate/6582262 to your computer and use it in GitHub Desktop.
Validation pop-up directive for angularjs
function ValidationPopup($timeout, $parse) {
return {
require: '?ngModel',
compile: function(element, attr) {
var msg = angular.element('<span>').addClass('validation-popup'),
errorMessages = {required: ' is Required', scwpMax: 'No bottles left'};
element.after(msg);
return function(scope, element, attr, ctrl) {
function popup(value) {
var show = scope.$submitted && !ctrl.$valid;
if (show && ctrl.$error) {
msg.css('left',element.width() + element.position().left);
msg.addClass('visible');
var errors = Object.keys(ctrl.$error);
errors = errors.map(function(key) {
return errorMessages[key];
}).filter(function(value) { return value; });
msg.text((element.attr('title')||'') + errors.join(',') + ' \u2715');
} else {
msg.removeClass('visible');
}
}
if (!ctrl) {
return;
}
var msg = element.next('.validation-popup');
msg.click(function(){msg.removeClass('visible');});
ctrl.$parsers.push(function(value) {
popup(value);
return value;
});
scope.$watchCollection('['+attr.ngModel+',$submitted]', popup);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment