Here's a trick.
Twitter Bootstrap tooltips (that Angular-UI relies upon) have an option to specify the trigger event with an additional attribute as in data-trigger="mouseenter"
. This gives you a way of changing the trigger programmatically (with Angular):
<input
ng-model="user.username"
name="username"
tooltip="Some text"
tooltip-trigger="{{{true: 'mouseenter', false: 'never'}[myForm.username.$invalid]}}"
/>
So when username
is $invalid, the tooltip-trigger
expression will evaluate to 'mouseenter'
and tooltip will show up. Otherwise, the trigger will evaluate to 'never'
which in return won't fire up the tooltip.
EDIT:
@cotten (in comments) mentions a scenario where tooltip gets stuck and won't go away even when model is valid. This happens when mouse stays over the input field while the text is being entered (and model becomes valid). As soon as model validation evaluates to true, the tooltip-trigger
will switch to "never".
UI Bootstrap uses a so called triggerMap
to determine on which mouse events to show/hide the tooltip.
// Default hide triggers for each show trigger
var triggerMap = {
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur'
};
As you may see, this map knows nothing about the "never" event, so it's unable to determine when to close the tooltip. So, to make out trick play nicely we only need to update this map with our own event pair and UI Bootstrap will then know what event to observe for closing the tooltip when tooltip-trigger
is set to "never".
app.config(['$tooltipProvider', function($tooltipProvider){
$tooltipProvider.setTriggers({
'mouseenter': 'mouseleave',
'click': 'click',
'focus': 'blur',
'never': 'mouseleave' // <- This ensures the tooltip will go away on mouseleave
});
}]);
PLUNKER
Note: $tooltip provider is exposed by the "ui.bootstrap.tooltip" module and it allows us to globally configure our tooltips in app configuration.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…