2

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.

Daniel Bonnell
  • 4,817
  • 9
  • 48
  • 88
  • Have you tried making it a directive and using jQlite's `on()` method to watch for an event? – Baruch Mar 27 '16 at 01:48
  • I'm not sure I follow. How would that prevent the click action from checking/unchecking the checkbox? – Daniel Bonnell Mar 27 '16 at 02:06
  • A good way of doing this is to have two scope variables. One for the real ``welcomeEmail.welcome_email_on`` value and one for the value associated with the checkbox. ``welcomeEmail.welcome_email_on_checkbox``. The reason being is that you need to process some code and only set ``welcomeEmail.welcome_email_on`` once some other code has run. This allows you to better in control of the flow and also make the code readable later. – Gene Mar 27 '16 at 03:17
  • But I still need to plug one of those variables into `ng-checked`. When a user clicks the toggle, its state is going to change, which doesn't really solve the issue. – Daniel Bonnell Mar 27 '16 at 16:03
  • [Possible duplicate](http://stackoverflow.com/questions/19496821/clicking-a-checkbox-with-ng-click-does-not-update-the-model) – Jeremy Klein May 17 '17 at 13:50

0 Answers0