Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

angularjs - Enable angular-ui tooltip on custom events

I am trying to use angular-ui's tooltip functionality to show my user that a particular field is invalid but it seems that the tooltip can be shown only on some pre-defined triggers. Is there any way by which I can trigger the tooltip except those triggers?

For example:

<input
    type="text"
    tooltip="Invalid name!"
    tooltip-position="right"
    tooltip-trigger="myForm.username.$invalid">
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...