2 * @license AngularJS v1.5.11
3 * (c) 2010-2017 Google, Inc. http://angularjs.org
6 (function(window, angular) {'use strict';
18 * The `ngMessages` module provides enhanced support for displaying messages within templates
19 * (typically within forms or when rendering message objects that return key/value data).
20 * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to
21 * show and hide error messages specific to the state of an input field, the `ngMessages` and
22 * `ngMessage` directives are designed to handle the complexity, inheritance and priority
23 * sequencing based on the order of how the messages are defined in the template.
25 * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude`
26 * `ngMessage` and `ngMessageExp` directives.
29 * The `ngMessages` directive allows keys in a key/value collection to be associated with a child element
30 * (or 'message') that will show or hide based on the truthiness of that key's value in the collection. A common use
31 * case for `ngMessages` is to display error messages for inputs using the `$error` object exposed by the
32 * {@link ngModel ngModel} directive.
34 * The child elements of the `ngMessages` directive are matched to the collection keys by a `ngMessage` or
35 * `ngMessageExp` directive. The value of these attributes must match a key in the collection that is provided by
36 * the `ngMessages` directive.
38 * Consider the following example, which illustrates a typical use case of `ngMessages`. Within the form `myForm` we
39 * have a text input named `myField` which is bound to the scope variable `field` using the {@link ngModel ngModel}
42 * The `myField` field is a required input of type `email` with a maximum length of 15 characters.
45 * <form name="myForm">
48 * <input type="email" ng-model="field" name="myField" required maxlength="15" />
50 * <div ng-messages="myForm.myField.$error" role="alert">
51 * <div ng-message="required">Please enter a value for this field.</div>
52 * <div ng-message="email">This field must be a valid email address.</div>
53 * <div ng-message="maxlength">This field can be at most 15 characters long.</div>
58 * In order to show error messages corresponding to `myField` we first create an element with an `ngMessages` attribute
59 * set to the `$error` object owned by the `myField` input in our `myForm` form.
61 * Within this element we then create separate elements for each of the possible errors that `myField` could have.
62 * The `ngMessage` attribute is used to declare which element(s) will appear for which error - for example,
63 * setting `ng-message="required"` specifies that this particular element should be displayed when there
64 * is no value present for the required field `myField` (because the key `required` will be `true` in the object
65 * `myForm.myField.$error`).
69 * By default, `ngMessages` will only display one message for a particular key/value collection at any time. If more
70 * than one message (or error) key is currently true, then which message is shown is determined by the order of messages
71 * in the HTML template code (messages declared first are prioritised). This mechanism means the developer does not have
72 * to prioritize messages using custom JavaScript code.
74 * Given the following error object for our example (which informs us that the field `myField` currently has both the
75 * `required` and `email` errors):
78 * <!-- keep in mind that ngModel automatically sets these error flags -->
79 * myField.$error = { required : true, email: true, maxlength: false };
81 * The `required` message will be displayed to the user since it appears before the `email` message in the DOM.
82 * Once the user types a single character, the `required` message will disappear (since the field now has a value)
83 * but the `email` message will be visible because it is still applicable.
85 * ### Displaying multiple messages at the same time
87 * While `ngMessages` will by default only display one error element at a time, the `ng-messages-multiple` attribute can
88 * be applied to the `ngMessages` container element to cause it to display all applicable error messages at once:
91 * <!-- attribute-style usage -->
92 * <div ng-messages="myForm.myField.$error" ng-messages-multiple>...</div>
94 * <!-- element-style usage -->
95 * <ng-messages for="myForm.myField.$error" multiple>...</ng-messages>
98 * ## Reusing and Overriding Messages
99 * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline
100 * template. This allows for generic collection of messages to be reused across multiple parts of an
104 * <script type="text/ng-template" id="error-messages">
105 * <div ng-message="required">This field is required</div>
106 * <div ng-message="minlength">This field is too short</div>
109 * <div ng-messages="myForm.myField.$error" role="alert">
110 * <div ng-messages-include="error-messages"></div>
114 * However, including generic messages may not be useful enough to match all input fields, therefore,
115 * `ngMessages` provides the ability to override messages defined in the remote template by redefining
116 * them within the directive container.
119 * <!-- a generic template of error messages known as "my-custom-messages" -->
120 * <script type="text/ng-template" id="my-custom-messages">
121 * <div ng-message="required">This field is required</div>
122 * <div ng-message="minlength">This field is too short</div>
125 * <form name="myForm">
128 * <input type="email"
135 * <!-- any ng-message elements that appear BEFORE the ng-messages-include will
136 * override the messages present in the ng-messages-include template -->
137 * <div ng-messages="myForm.myEmail.$error" role="alert">
138 * <!-- this required message has overridden the template message -->
139 * <div ng-message="required">You did not enter your email address</div>
141 * <!-- this is a brand new message and will appear last in the prioritization -->
142 * <div ng-message="email">Your email address is invalid</div>
144 * <!-- and here are the generic error messages -->
145 * <div ng-messages-include="my-custom-messages"></div>
150 * In the example HTML code above the message that is set on required will override the corresponding
151 * required message defined within the remote template. Therefore, with particular input fields (such
152 * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied
153 * while more generic messages can be used to handle other, more general input errors.
155 * ## Dynamic Messaging
156 * ngMessages also supports using expressions to dynamically change key values. Using arrays and
157 * repeaters to list messages is also supported. This means that the code below will be able to
158 * fully adapt itself and display the appropriate message when any of the expression data changes:
161 * <form name="myForm">
164 * <input type="email"
170 * <div ng-messages="myForm.myEmail.$error" role="alert">
171 * <div ng-message="required">You did not enter your email address</div>
172 * <div ng-repeat="errorMessage in errorMessages">
173 * <!-- use ng-message-exp for a message whose key is given by an expression -->
174 * <div ng-message-exp="errorMessage.type">{{ errorMessage.text }}</div>
180 * The `errorMessage.type` expression can be a string value or it can be an array so
181 * that multiple errors can be associated with a single error message:
186 * <input type="email"
187 * ng-model="data.email"
193 * <div ng-messages="myForm.myEmail.$error" role="alert">
194 * <div ng-message-exp="'required'">You did not enter your email address</div>
195 * <div ng-message-exp="['minlength', 'maxlength']">
196 * Your email must be between 5 and 100 characters long
201 * Feel free to use other structural directives such as ng-if and ng-switch to further control
202 * what messages are active and when. Be careful, if you place ng-message on the same element
203 * as these structural directives, Angular may not be able to determine if a message is active
204 * or not. Therefore it is best to place the ng-message on a child element of the structural
208 * <div ng-messages="myForm.myEmail.$error" role="alert">
209 * <div ng-if="showRequiredError">
210 * <div ng-message="required">Please enter something</div>
216 * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and
217 * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from
218 * the DOM by the `ngMessages` directive.
220 * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS
221 * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no
222 * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can
223 * hook into the animations whenever these classes are added/removed.
225 * Let's say that our HTML code for our messages container looks like so:
228 * <div ng-messages="myMessages" class="my-messages" role="alert">
229 * <div ng-message="alert" class="some-message">...</div>
230 * <div ng-message="fail" class="some-message">...</div>
234 * Then the CSS animation code for the message container looks like so:
238 * transition:1s linear all;
240 * .my-messages.ng-active {
241 * // messages are visible
243 * .my-messages.ng-inactive {
244 * // messages are hidden
248 * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter
249 * and leave animation is triggered for each particular element bound to the `ngMessage` directive.
251 * Therefore, the CSS code for the inner messages looks like so:
255 * transition:1s linear all;
258 * .some-message.ng-enter {}
259 * .some-message.ng-enter.ng-enter-active {}
261 * .some-message.ng-leave {}
262 * .some-message.ng-leave.ng-leave-active {}
265 * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate.
267 angular.module('ngMessages', [], function initAngularHelpers() {
268 // Access helpers from angular core.
269 // Do it inside a `config` block to ensure `window.angular` is available.
270 forEach = angular.forEach;
271 isArray = angular.isArray;
272 isString = angular.isString;
273 jqLite = angular.element;
283 * `ngMessages` is a directive that is designed to show and hide messages based on the state
284 * of a key/value object that it listens on. The directive itself complements error message
285 * reporting with the `ngModel` $error object (which stores a key/value state of validation errors).
287 * `ngMessages` manages the state of internal messages within its container element. The internal
288 * messages use the `ngMessage` directive and will be inserted/removed from the page depending
289 * on if they're present within the key/value object. By default, only one message will be displayed
290 * at a time and this depends on the prioritization of the messages within the template. (This can
291 * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)
293 * A remote template can also be used to promote message reusability and messages can also be
296 * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
300 * <!-- using attribute directives -->
301 * <ANY ng-messages="expression" role="alert">
302 * <ANY ng-message="stringValue">...</ANY>
303 * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
304 * <ANY ng-message-exp="expressionValue">...</ANY>
307 * <!-- or by using element directives -->
308 * <ng-messages for="expression" role="alert">
309 * <ng-message when="stringValue">...</ng-message>
310 * <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
311 * <ng-message when-exp="expressionValue">...</ng-message>
315 * @param {string} ngMessages an angular expression evaluating to a key/value object
316 * (this is typically the $error object on an ngModel instance).
317 * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true
320 * <example name="ngMessages-directive" module="ngMessagesExample"
321 * deps="angular-messages.js"
322 * animations="true" fixBase="true">
323 * <file name="index.html">
324 * <form name="myForm">
334 * <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>
336 * <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
337 * <div ng-message="required">You did not enter a field</div>
338 * <div ng-message="minlength">Your field is too short</div>
339 * <div ng-message="maxlength">Your field is too long</div>
343 * <file name="script.js">
344 * angular.module('ngMessagesExample', ['ngMessages']);
348 .directive('ngMessages', ['$animate', function($animate) {
349 var ACTIVE_CLASS = 'ng-active';
350 var INACTIVE_CLASS = 'ng-inactive';
353 require: 'ngMessages',
355 controller: ['$element', '$scope', '$attrs', function NgMessagesCtrl($element, $scope, $attrs) {
358 var nextAttachId = 0;
360 this.getAttachId = function getAttachId() { return nextAttachId++; };
362 var messages = this.messages = {};
363 var renderLater, cachedCollection;
365 this.render = function(collection) {
366 collection = collection || {};
369 cachedCollection = collection;
371 // this is true if the attribute is empty or if the attribute value is truthy
372 var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||
373 isAttrTruthy($scope, $attrs.multiple);
375 var unmatchedMessages = [];
376 var matchedKeys = {};
377 var messageItem = ctrl.head;
378 var messageFound = false;
379 var totalMessages = 0;
381 // we use != instead of !== to allow for both undefined and null values
382 while (messageItem != null) {
384 var messageCtrl = messageItem.message;
386 var messageUsed = false;
388 forEach(collection, function(value, key) {
389 if (!messageUsed && truthy(value) && messageCtrl.test(key)) {
390 // this is to prevent the same error name from showing up twice
391 if (matchedKeys[key]) return;
392 matchedKeys[key] = true;
395 messageCtrl.attach();
401 // unless we want to display multiple messages then we should
402 // set a flag here to avoid displaying the next message in the list
403 messageFound = !multiple;
405 unmatchedMessages.push(messageCtrl);
408 messageItem = messageItem.next;
411 forEach(unmatchedMessages, function(messageCtrl) {
412 messageCtrl.detach();
415 if (unmatchedMessages.length !== totalMessages) {
416 $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS);
418 $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);
422 $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);
424 // If the element is destroyed, proactively destroy all the currently visible messages
425 $element.on('$destroy', function() {
426 forEach(messages, function(item) {
427 item.message.detach();
431 this.reRender = function() {
434 $scope.$evalAsync(function() {
435 if (renderLater && cachedCollection) {
436 ctrl.render(cachedCollection);
442 this.register = function(comment, messageCtrl) {
443 var nextKey = latestKey.toString();
444 messages[nextKey] = {
447 insertMessageNode($element[0], comment, nextKey);
448 comment.$$ngMessageNode = nextKey;
454 this.deregister = function(comment) {
455 var key = comment.$$ngMessageNode;
456 delete comment.$$ngMessageNode;
457 removeMessageNode($element[0], comment, key);
458 delete messages[key];
462 function findPreviousMessage(parent, comment) {
463 var prevNode = comment;
464 var parentLookup = [];
466 while (prevNode && prevNode !== parent) {
467 var prevKey = prevNode.$$ngMessageNode;
468 if (prevKey && prevKey.length) {
469 return messages[prevKey];
472 // dive deeper into the DOM and examine its children for any ngMessage
473 // comments that may be in an element that appears deeper in the list
474 if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) === -1) {
475 parentLookup.push(prevNode);
476 prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];
477 } else if (prevNode.previousSibling) {
478 prevNode = prevNode.previousSibling;
480 prevNode = prevNode.parentNode;
481 parentLookup.push(prevNode);
486 function insertMessageNode(parent, comment, key) {
487 var messageNode = messages[key];
489 ctrl.head = messageNode;
491 var match = findPreviousMessage(parent, comment);
493 messageNode.next = match.next;
494 match.next = messageNode;
496 messageNode.next = ctrl.head;
497 ctrl.head = messageNode;
502 function removeMessageNode(parent, comment, key) {
503 var messageNode = messages[key];
505 var match = findPreviousMessage(parent, comment);
507 match.next = messageNode.next;
509 ctrl.head = messageNode.next;
515 function isAttrTruthy(scope, attr) {
516 return (isString(attr) && attr.length === 0) || //empty attribute
517 truthy(scope.$eval(attr));
520 function truthy(val) {
521 return isString(val) ? val.length : !!val;
527 * @name ngMessagesInclude
532 * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template
533 * code from a remote template and place the downloaded template code into the exact spot
534 * that the ngMessagesInclude directive is placed within the ngMessages container. This allows
535 * for a series of pre-defined messages to be reused and also allows for the developer to
536 * determine what messages are overridden due to the placement of the ngMessagesInclude directive.
540 * <!-- using attribute directives -->
541 * <ANY ng-messages="expression" role="alert">
542 * <ANY ng-messages-include="remoteTplString">...</ANY>
545 * <!-- or by using element directives -->
546 * <ng-messages for="expression" role="alert">
547 * <ng-messages-include src="expressionValue1">...</ng-messages-include>
551 * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
553 * @param {string} ngMessagesInclude|src a string value corresponding to the remote template.
555 .directive('ngMessagesInclude',
556 ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) {
560 require: '^^ngMessages', // we only require this for validation sake
561 link: function($scope, element, attrs) {
562 var src = attrs.ngMessagesInclude || attrs.src;
563 $templateRequest(src).then(function(html) {
564 if ($scope.$$destroyed) return;
566 if (isString(html) && !html.trim()) {
567 // Empty template - nothing to compile
568 replaceElementWithMarker(element, src);
570 // Non-empty template - compile and link
571 $compile(html)($scope, function(contents) {
572 element.after(contents);
573 replaceElementWithMarker(element, src);
581 function replaceElementWithMarker(element, src) {
582 // A comment marker is placed for debugging purposes
583 var comment = $compile.$$createComment ?
584 $compile.$$createComment('ngMessagesInclude', src) :
585 $document[0].createComment(' ngMessagesInclude: ' + src + ' ');
586 var marker = jqLite(comment);
587 element.after(marker);
589 // Don't pollute the DOM anymore by keeping an empty directive element
601 * `ngMessage` is a directive with the purpose to show and hide a particular message.
602 * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element
603 * must be situated since it determines which messages are visible based on the state
604 * of the provided key/value map that `ngMessages` listens on.
606 * More information about using `ngMessage` can be found in the
607 * {@link module:ngMessages `ngMessages` module documentation}.
611 * <!-- using attribute directives -->
612 * <ANY ng-messages="expression" role="alert">
613 * <ANY ng-message="stringValue">...</ANY>
614 * <ANY ng-message="stringValue1, stringValue2, ...">...</ANY>
617 * <!-- or by using element directives -->
618 * <ng-messages for="expression" role="alert">
619 * <ng-message when="stringValue">...</ng-message>
620 * <ng-message when="stringValue1, stringValue2, ...">...</ng-message>
624 * @param {expression} ngMessage|when a string value corresponding to the message key.
626 .directive('ngMessage', ngMessageDirectiveFactory())
637 * `ngMessageExp` is the same as {@link directive:ngMessage `ngMessage`}, but instead of a static
638 * value, it accepts an expression to be evaluated for the message key.
642 * <!-- using attribute directives -->
643 * <ANY ng-messages="expression">
644 * <ANY ng-message-exp="expressionValue">...</ANY>
647 * <!-- or by using element directives -->
648 * <ng-messages for="expression">
649 * <ng-message when-exp="expressionValue">...</ng-message>
653 * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.
655 * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.
657 .directive('ngMessageExp', ngMessageDirectiveFactory());
659 function ngMessageDirectiveFactory() {
660 return ['$animate', function($animate) {
663 transclude: 'element',
664 priority: 1, // must run before ngBind, otherwise the text is set on the comment
666 require: '^^ngMessages',
667 link: function(scope, element, attrs, ngMessagesCtrl, $transclude) {
668 var commentNode = element[0];
671 var staticExp = attrs.ngMessage || attrs.when;
672 var dynamicExp = attrs.ngMessageExp || attrs.whenExp;
673 var assignRecords = function(items) {
677 : items.split(/[\s,]+/))
679 ngMessagesCtrl.reRender();
683 assignRecords(scope.$eval(dynamicExp));
684 scope.$watchCollection(dynamicExp, assignRecords);
686 assignRecords(staticExp);
689 var currentElement, messageCtrl;
690 ngMessagesCtrl.register(commentNode, messageCtrl = {
691 test: function(name) {
692 return contains(records, name);
695 if (!currentElement) {
696 $transclude(function(elm, newScope) {
697 $animate.enter(elm, null, element);
698 currentElement = elm;
700 // Each time we attach this node to a message we get a new id that we can match
701 // when we are destroying the node later.
702 var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId();
704 // in the event that the element or a parent element is destroyed
705 // by another structural directive then it's time
706 // to deregister the message from the controller
707 currentElement.on('$destroy', function() {
708 if (currentElement && currentElement.$$attachId === $$attachId) {
709 ngMessagesCtrl.deregister(commentNode);
710 messageCtrl.detach();
718 if (currentElement) {
719 var elm = currentElement;
720 currentElement = null;
729 function contains(collection, key) {
731 return isArray(collection)
732 ? collection.indexOf(key) >= 0
733 : collection.hasOwnProperty(key);
739 })(window, window.angular);