0

I just want to toggle between radio buttons. The value starts with null.

If 0, first checkbox selected, second unselected

if 1, second checkbox selected, first unselected

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="">
  <span>Value: {{vm.value}}</span> <br>

  <input type="radio" ng-model="vm.value" value={{vm.value}}
         ng-click="vm.value = 0" ng-checked="vm.value == 0"
         ng-init="vm.value = null" />

  <input type="radio" ng-model="vm.value" ng-click="vm.value = 1"
         value={{vm.value}} ng-checked="vm.value == 1" />
</div>

Any help?

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Tiago
  • 69
  • 1
  • 7
  • 3
    You need to add the same name as a property to each input type radio. Add `name="myValues"` to each input as an attribute. – Nicolae Maties Nov 08 '19 at 11:16

2 Answers2

2

Theres no need to use ng-click and ng-checked.

  • You have to set the name of each radio to the same, like name="myRadios" in the example below

  • You have to set the value to 0 or 1 instead of {{vm.value}} or bind it to your wanted data.

    (Your ng-model="vm.value" value="{{vm.value}}" makes no sense, because ng-model= is the part where you want to store the value and value= is the part where the value comes from.)


<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="">
  <span>Value: {{vm.value}}</span> <br>

  <input type="radio" name="myRadios" ng-model="vm.value" value="0" ng-init="vm.value = null" />

  <input type="radio" name="myRadios" ng-model="vm.value" value="1" />
</div>
jsadev.net
  • 2,800
  • 1
  • 16
  • 28
  • I can't hardcode the value. This comes from the db – Tiago Nov 08 '19 at 11:33
  • 1
    @Tiago: the value is irrelevant to the answer, the important part is that the `name` attribute-value is the same for each related ``. – David Thomas Nov 08 '19 at 11:36
  • To bind your value to the data from your db you could use `value="{{yourvalue}}"` or [`ng-value`](https://docs.angularjs.org/api/ng/directive/ngValue). But note that your `value="{{vm.value}}"` makes no sense, because you want to store the selection into `vm.value` and not to get the values from it. – jsadev.net Nov 08 '19 at 11:52
-1

give your inputs same name!

<input type="radio" name="radio ng-model="vm.value" value={{vm.value}}
       ng-click="vm.value = 0" ng-checked="vm.value == 0"
       ng-init="vm.value = null" />

<input type="radio" name="radio ng-model="vm.value"
       ng-click="vm.value = 1" value={{vm.value}}
       ng-checked="vm.value == 1" />
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Unes
  • 356
  • 3
  • 8