Radio buttons ng-required checkbox like

116 Views Asked by At

I'm having a little problem with some radio buttons inside my form. I know that a checkbox could do this in a real easy way but, you know, customer asking for this.

So, this is the form part:

<label>
    <span>Acconsento*</span>
    <input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" ng-required="!ctrl.isValidPrivacy()"/>
</label>
<label>
    <span>Non acconsento</span>
    <input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1"/>
</label>

With respective JS part:

self.isValidPrivacy = function () {
    return (!self.utente.privacy_1 || self.utente.privacy_1 == 0) ? false : true;
};

and ctrl.utente.privacy_1 must be == 1.

After trying ng-required="ctrl.utente.privacy_1 != 1"
or ng-required="!ctrl.utente.privacy_1 (removing value="0" from 2nd radio input) I still haven't found a way to accomplish this.

ctrl.utente.privacy_1 == 0 isn't shown as validation error, and it can't be selected by default (ctrl.utente.privacy_1 can't be false by default)

All others answers on StackOverflow doesn't solve my problem

1

There are 1 best solutions below

4
On

Well, I think you have some messed concepts...

First, you don't need a ternary operator to discern between true and false, just return the result of the comparision:

return (!self.utente.privacy_1 || self.utente.privacy_1 == 0);

would be enough. That said, you don't even need a function to check for this, you could do it directly on the attribute, since it's a simple check:

<... ng-required="!$ctrl.utente.privacy_1 || $ctrl.utente.privacy_1 == 0" .../>

That said, I don't understand why do you need an ng-required at all, maybe you've missunderstood its meaning... ng-required it's used to force the user to give a value to an input field, is NOT for checking it's value, that is what it seems you're trying to do. If you want to be sure that the user selects one of the two options just use the html attribute 'required' on both inputs, and that's enough.

<label>
    <span>Acconsento*</span>
    <input type="radio" name="privacy_1" value="1" ng-model="ctrl.utente.privacy_1" required />
</label>
<label>
    <span>Non acconsento</span>
    <input type="radio" name="privacy_1" value="0" ng-model="ctrl.utente.privacy_1" required />
</label>