In AngularJS how to uncheck a radio button to make all objects become false


I have an array with many "contact" objects inside. Only one contact can be the primary contact (primary: true).

I also have a radio button to select which contact is the primary.

Q: How can I make one contact primary and deactivate all of the others (primary: false)? so only one object have the property (primary: true) and the rest false?

My example:

.controller('ExampleController', ['$scope',
        function($scope) {
        $scope.addContList = [
                email: "",
                jobTitle: "clerk",
                name: "nico2",
                phone: "1",
                primary: true
                email: "",
                jobTitle: "director",
                name: "david",
                phone: "1",
                primary: false
          $scope.$watch('addContList', function() {
            console.log('changed', JSON.stringify($scope.addContList, null, 2))
          }, true)


Here is the view

<tr ng-repeat="contact in addContList">
            <label class="radio-inline">
              <input type="radio" value="" name="ui_cont" ng-model="contact.primary" ng-value="true">
          <td>{{ }} value = {{contact.primary}} </td>
Problem courtesy of: lito


You would want to add an ngChange event to your input and change all other inputs to false when one gets set to true. I have updated your Plnkr here:

<input type="radio" value="" name="ui_cont" ng-change='changeOnPrimary(contact)' ng-model="contact.primary" ng-value="true">

Then in your controller:

$scope.changeOnPrimary = function(selectedContact) {
  // iterate over your whole list
  angular.forEach($scope.addContList, function(contact) {
    // set primary to false for all contacts excepts selected
    if ( !== {
      contact.primary = false;

Please note: the only reason I'm comparing the name field of the object is because there is no unique identifier to compare with. In real code, you would want to compare against an ID rather than a name field.

Solution courtesy of: mcranston18


You can define a new scope property

$scope.primary = null

Then you can define a listener

$scope.$watch("primary", function(value) {
  $scope.addContList.forEach(function(contact) {
    contact.primary = angular.equals(value, contact);

and you can define a default value after defining the list

$scope.primary = $scope.addContList[0];

and in the html you change the input line in

<input type="radio" value="" name="ui_cont" ng-model="$parent.primary" ng-value="contact">

You need to use $parent.primary instead of primary, because ng-repeat defines a new child scope.


Discussion courtesy of: robkub

This recipe can be found in it's original form on Stack Over Flow.