Raihan
Raihan

Reputation: 4001

AngularJS: Hide the form with one click without showing error message

This is what my form looks like in the plunker.

enter image description here

I've added ng-message validation on my email field. To make it more user-friendly I'm showing the error message on blur and to achieve this I used ng-model-options="{ updateOn: 'blur' }". I also have a Hide button to hide the form. So far it works fine.

Problem:

  1. If I type an invalid email address in the field and click outside, error message shows. But If I type an invalid email and click the Hide Form button I want to hide the form instead of showing the error message first.

N.B. Strangely sometimes Hide Form works as expected but most of the time it does not. and I'm not sure why.

enter image description here

  1. It's optional: Can I hide my error message again if I focus back the input field? I think it'll improve the UX a bit.

Working Plunker

Upvotes: 0

Views: 43

Answers (1)

Tom Mettam
Tom Mettam

Reputation: 2963

1 - This is happening because the button is being moved away from the mouse cursor as soon as the text box loses focus, which is causing the click to cancel. Simple fix:

Change

ng-click="canceled = true"

to

ng-mousedown="canceled = true"

If you don't want this instant behaviour on mouse down, then you can do something like

ng-mousedown="mousedown = true"
ng-mouseup="mousedown = false"

and add !mousedown to the ng-if of the help-block. Or just position the hide button so that it doesn't move when the error block displays. You could use position: absolute, or something like ng-style="{'visibility' : condition ? 'visible' : 'hidden'}" on the help block so it doesn't affect the layout when hidden.

2 - Yes, sure.

In the input element:

ng-focus="focused = true"
ng-blur="focused = false"

Then in the ng-if of the help-block:

ng-if="userForm.email.$touched && !focused"

Plunkr

Upvotes: 1

Related Questions