Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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: http://plnkr.co/edit/7gxI7if9nC7hAMQES1eu?p=preview

<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 (selectedContact.name !== contact.name) {
      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 2:

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.

see http://plnkr.co/edit/5pvatBNwnrJhGzKhOIys?p=preview


Post a Comment for "In AngularJS How To Uncheck A Radio Button To Make All Objects Become False"