0

I'm using Angularjs and I have two radio buttons with the same name access and different model fields model.field1 and model.field2, so I need to update the model when selection change, initially model.field1 and model.field2 are set to false, and I want to set the model value to true when cheched and false when not checked, how can I do that?

<input type="radio" id="r1" data-ng-model="model.field1" name="access"><span>R 1</span>
<input type="radio" id="r2" data-ng-model="model.field2" name="access"><span>R 2</span>

I appreciate any help, thanks

2 Answers 2

1

I believe the preferred way to do this is with a single variable, and the value attribute, like this:

<input type="radio" id="r1" data-ng-model="model.field1" value="1" name="access"><span>R 1</span>
<input type="radio" id="r2" data-ng-model="model.field1" value="2" name="access"><span>R 2</span>
{{model.field1}}

This will set the variable model.field1 to 1 or 2 depending on which is selected. It is undefined if nothing is selected. Let me know if this will work for your use case.

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

3 Comments

Thanks @Dested, I know that way but in this case I have two variables for representing separated attributes in order to give access to users for example: user.readWrite and user.readOnly and a single variable is not so useful for me. Have you any other idea? Thanks a lot
The only way I can think off of hand is to set value to "true" in both cases, default them both to false, and use a series of watches on all of the applicable fields to set them to false when any one of them gets set to true... Another option would be to use 0 for readOnly, 1 for readWrite, and to a watch on THAT value, and set the actual variables representing the accessibility appropriately.
Thanks Dested, Your suggestion was very useful for me. I solved the problem watching the variable value and setting the actual variables appropriately. Cheers!!
1

You need to set them with a single scope variable and ng-value as shown in the Angular docs (https://docs.angularjs.org/api/ng/input/input%5Bradio%5D).

<input type="radio" id="r1" ng-model="model.field1" ng-value="1" name="access"><span>R 1</span>
<input type="radio" id="r2" ng-model="model.field1" ng-value="2" name="access"><span>R 2</span>

1 Comment

Thanks @MBielski, I know that way but in this case I have two variables for representing separated attributes in order to give access to users for example: user.readWrite and user.readOnly and a single variable is not so useful for me. Have you any other idea? Thanks a lot

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.