Ashu Ashu - 17 days ago 9
AngularJS Question

how to select one primary contact on listing of contacts in ng-repeat by radio button

I have list of contacts and repeating with ng-repeat how to make one primary contact by selecting radio button .

<div class="col-sm-12" ng-repeat='contact in acc.contacts'>

<div class="col-xs-2" ng-class="{'error':(sub && !contact.isPrimary)}">
<input type="radio" name='isPrimary'
ng-model='contact.isPrimary' ng-value="true">
</div>

<div class="col-xs-2" ng-class="{'error':(sub && !contact.name)}">
<input type="text" ng-model='contact.name'>
</div>

</div>
</div>


my json is look like

{"contacts":[{"isPrimary":false,"name":null,},{"isPrimary":false,"name":null},{"isPrimary":false,"name":null]}


i want isPrimary should be true for one , but it does not set false when radio button got deselected

Answer

Because you use the radio button in an ng-repeat and the ng-model is a property of the repeated item, you can do it like this:

<div class="col-xs-2" ng-class="{'error':(sub && !contact.isPrimary)}">
    <input type="radio" name='isPrimary'
           ng-value="true"
           ng-change="primaryClicked(contact)">
</div>

And in your controller:

$scope.primaryClicked = function(contact) {
    // Set all others on false
    for (var i = 0; i < $scope.acc.contacts.length; i++) {
        $scope.acc.contacts[i].isPrimary = false;
    }

    // Set current on true
    contact.isPrimary = true;
}
Comments