@@ -417,13 +417,6 @@ angular.module('ngMessages', [], function initAngularHelpers() {
417
417
418
418
$scope . $watchCollection ( $attrs . ngMessages || $attrs [ 'for' ] , ctrl . render ) ;
419
419
420
- // If the element is destroyed, proactively destroy all the currently visible messages
421
- $element . on ( '$destroy' , function ( ) {
422
- forEach ( messages , function ( item ) {
423
- item . message . detach ( ) ;
424
- } ) ;
425
- } ) ;
426
-
427
420
this . reRender = function ( ) {
428
421
if ( ! renderLater ) {
429
422
renderLater = true ;
@@ -498,6 +491,9 @@ angular.module('ngMessages', [], function initAngularHelpers() {
498
491
function removeMessageNode ( parent , comment , key ) {
499
492
var messageNode = messages [ key ] ;
500
493
494
+ // This message node may have already been removed by a call to deregister()
495
+ if ( ! messageNode ) return ;
496
+
501
497
var match = findPreviousMessage ( parent , comment ) ;
502
498
if ( match ) {
503
499
match . next = messageNode . next ;
@@ -702,6 +698,8 @@ function ngMessageDirectiveFactory() {
702
698
// by another structural directive then it's time
703
699
// to deregister the message from the controller
704
700
currentElement . on ( '$destroy' , function ( ) {
701
+ // If the message element was removed via a call to `detach` then `currentElement` will be null
702
+ // So this handler only handles cases where something else removed the message element.
705
703
if ( currentElement && currentElement . $$attachId === $$attachId ) {
706
704
ngMessagesCtrl . deregister ( commentNode ) ;
707
705
messageCtrl . detach ( ) ;
@@ -719,6 +717,14 @@ function ngMessageDirectiveFactory() {
719
717
}
720
718
}
721
719
} ) ;
720
+
721
+ // We need to ensure that this directive deregisters itself when it no longer exists
722
+ // Normally this is done when the attached element is destroyed; but if this directive
723
+ // gets removed before we attach the message to the DOM there is nothing to watch
724
+ // in which case we must deregister when the containing scope is destroyed.
725
+ scope . $on ( '$destroy' , function ( ) {
726
+ ngMessagesCtrl . deregister ( commentNode ) ;
727
+ } ) ;
722
728
}
723
729
} ;
724
730
} ] ;
0 commit comments