Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : $pristine for ng-check checked inputs

I have a form with about 100 questions, each with a radio and some checkboxes, so I need the user to be able to save the form and load it later. I need also to check which ones the user changed in this session.

This question solves the problem: How can I denote which input fields have changed in AngularJS

The second answer (storing the old and current values of the model and comparing both) does it. However, if I wanted to go with the $pristine solution I have a problem. Unchecking a ng-checked box does not change it's $pristine value. The $pristine value becomes false only by checking the box again after the uncheck.

I know I'm not suposed to use ng-model with ng-check but I get the answers from the server in values of either 1 or 0. This values used as model do not check the checkboxes.

ng-model="question.answer"  //will not check the box
ng-check="question.answer"  //does check the box

Value comes as 1 from the server. Unchecking and checking the box changes it to 'true'

<input ng-model="question.answer" ng-checked="question.answer" 
type="checkbox" name="{{'answer' + question.id}}"/>

Heres a plnkr: http://plnkr.co/edit/3xcI0Yq9WPZ1IxJJjKGt?p=preview

like image 365
Luís da Mota Avatar asked Feb 22 '26 14:02

Luís da Mota


1 Answers

What you need is to set 1 and 0 to be considered as true and false values respectively. You can use ng-true-value and ng-false-value to have that set up. You dont have to deal with converting 1/0 to true/false and also can get rid of ng-checked and use ng-model itself effectively.

<input ng-model="question.answer" 
            ng-true-value="1" 
            ng-false-value="0" type="checkbox" name="{{'answer' + question.id}}" />

Plnkr

like image 156
PSL Avatar answered Feb 24 '26 05:02

PSL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!