2

To be specific: I have two radio buttons and their ng-model value must be boolean. Since this is not possible with normal html value property I found useful Angularjs ng-value. Problem is when I want to do some validation, when radio button ng-value="false" is selected it recognizes it as an empty ng-model and we have validation error.

Example: http://plnkr.co/edit/lvdNHZoSSN1nM6uLyc0Q?p=preview

Any clue how to tackle this?

3
  • Use a checkbox if you have only one truthy value. Commented Apr 16, 2013 at 23:43
  • I cannot use checkbox. Client wants to have 2 radio buttons and possibility that value can be null (both unselected) Commented Apr 17, 2013 at 16:55
  • If the client wants the radio button "look" but doesn't care about the type attribute on the input, then you could restyle a checkbox to look like a radio button using CSS. Commented Jun 2, 2013 at 21:37

3 Answers 3

3

This is a bug.

value="true/false" won't work because your radio inputs won't be initialized and checked correctly when your model is loaded, but ng-value="true/false" won't work because "false" selections will cause the form to be invalid.

I was having the same problem and reported it as an issue, but since there's no telling when it will be resolved, I also came up with a workaround: ng-boolean-radio

It basically converts your model's boolean true / false values into string "true" / "false" values, which match your form's string value="true/false" attributes. This will allow the corresponding radio inputs to be checked by default when the model loads. It will also allow you to save "false" values because "false" != false.

Finally, it preserves the boolean datatype by converting the string "true" / "false" values back to boolean true / false before saving them in the model.

I hope that helps!

Sign up to request clarification or add additional context in comments.

Comments

2

http://plnkr.co/edit/Y5vDuTug0kvS3Ut58Lz9?p=preview

Problem is in the required attribute.

I believe using ng-required="!user.gender" is what you're looking for.

Edit: it seems that ng-required, while slightly better, still doesn't work fully.

My recommendation is to omit require completely and initialize your model with a default value:

{gender: true} (false will work too).

1 Comment

It is not working. It is working only if you select first true and then false. If you select false, nothing happens.
0

I had this problem, too. Michael Moussa's directive was very good for debugging what the checkboxe's/radio button's actual modelValue is. As it turned out, a modelValue of false arrived undefined at the checkbox/radio button. Updating (from 1.2.0) to angular 1.2.5 fixed the problem for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.