Take a look at this example:
http://codepen.io/troywarr/pen/zxWLeZ
I'm working on a form similar to the one in the example where users can opt out of entering certain data by clicking a checkbox. I am using ng-disabled
to disable the relevant field ("Age" in my case) when the checkbox is checked.
It works well if they click the checkbox before entering data into the field. However, if they enter data first and then click the checkbox to disable it, the data remains in both the model and the view; it is just locked from changes.
Here's what I want to achieve:
Even if the user enters data into a field that they later disable, remove that data from the model. For instance, if the checkbox is checked and both "Name" and "Age" are filled out, I would like the user object to only be:
{ "name": "John" }
instead of:
{ "name": "John", "age": 35 }
Additionally, I would like to:
- Clear the data from the view as well (emptying the "Age" field).
- Make the data removal reversible. If a user enters their age as
35
, then checks the checkbox to disable it, the "Age" field should empty (and theuser
model should lose theage
property). When they uncheck the checkbox, the value35
should return to both the "Age" field and the model. In other words, preserving their work if they change their mind. - Implement this approach at scale with a reusable directive or a simple expression, as my form is complex with many instances of this behavior and there will be more similar forms in the future.
My initial idea was to either:
- Set
ng-model
for the "Age" field conditionally based on the checkbox state - Unbind the "Age" field when the checkbox is checked and re-bind it when unchecked
But how can I accomplish this? Is there a simpler method?
I have tried various combinations of directives but haven't found a solution yet. I am now exploring the documentation, but would appreciate some guidance. Thank you!