Created
September 16, 2013 15:34
-
-
Save jamie-pate/6582262 to your computer and use it in GitHub Desktop.
Validation pop-up directive for angularjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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