Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable angular-ui tooltip on custom events

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-triggerexpression 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-triggerwill 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.


I tried something different

tooltip="{{(myForm.input1id.$invalid) ? 'You have an error with this field' : ''}}"

This way, my tooltip only has something written when the input is invalid, and if it doesn't have anything written, the tooltip doesn't show.


From version 0.12.0 onwards, tooltip-tigger is no longer observable (so you can't change it programatically).

You can use tooltip-enable to get the same behavior. See more details here: https://github.com/angular-ui/bootstrap/issues/3372


You can also add the tooltip-enable instead of the tooltip-trigger on your field.

<input
    type="text"
    tooltip="Invalid name!"
    tooltip-position="right"
    tooltip-enable="{{myForm.username.$invalid}}">

In this case if the username is invalid ($invalid returns true) the tooltip will appear.