Luís da Mota
Luís da Mota

Reputation: 58

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

Upvotes: 3

Views: 3502

Answers (1)

PSL
PSL

Reputation: 123739

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

Upvotes: 5

Related Questions