samedi 26 mars 2016

ng-checked/ng-model prevent change to model when user clicks checkbox

I'm building a simple form with a toggle. I want to bind the toggle to my model, welcomeEmail.welcome_email_on. When I click the toggle, I want to call toggleWelcomeEmail() in my controller. This function will check if the new state is true or false and then do something. For example, if the toggle was off, and the user clicks it, it should turn on. If it is already on, and the user clicks it, the toggleWelcomeEmail() function should display a confirmation prompt and the toggle should remain on until the user confirms the action in the prompt.

The problem I'm having is that it seems the default behavior of ng-model and ng-checked on a checkbox is to update the model when the user clicks the checkbox. What I want to do is prevent the default. I want the state of my checkbox/toggle to reflect the model, however I do not want the model to update when it is clicked. Instead I prefer to call toggleWelcomeEmail().

My question is, how can I accomplish this? I've tried using both ng-checked and ng-model, but both behave the same way. I know I could create two toggles and just show/hide them based off the state of welcomeEmail.welcome_email_on, but then I'd loose the nice toggle animation I have. I've also tried the obvious approach of putting an $event.stopPropagation() on my ng-click action, however that had no effect.

I've created a fiddle to demonstrate the problem.




Aucun commentaire:

Enregistrer un commentaire