Baki
Baki

Reputation: 614

Toggle true/false through radio buttons in AngularJS (inside of ng-repeat)

Hej, I've got an "almost" working fiddle. I have a list of items and I want to change their value if their radiobutton is selected. Here's the code:

CodePen: http://codepen.io/anon/pen/MyvQoP

Html:

<div ng-app="myapp" ng-controller="myController">
  <div ng-repeat="food in foodList">
    <span>{{food.name}}</span>
    <input type="radio" ng-model="food.selected" name="radiofood" ng-value="true">
  </div>
</div>

JS:

angular.module('myapp', []).controller("myController", myController)

function myController($scope) {
  $scope.foodList = [
    {
      name: 'banana',
      selected: 'false'
    },
    {
      name: 'orange',
      selected: 'false'
    },
    {
      name: 'apple',
      selected: 'false'
    }
  ]
}

The problem:
A radiobutton once clicked, changes it's value to true but clicking another one does not change the previous one to false. So if you click each one of them, one by one, all of them will be true. I only want one to have the true value.

Thanks

--- Edit 2016-03-31 ---
I was looking for a solution without writing a custom fuction but it turns out this can't be done. I've marked @Ankit Pundhir answer as the best one but it wasn't exaclty what i was aiming for.

Upvotes: 1

Views: 1894

Answers (2)

pokemzok
pokemzok

Reputation: 1709

The most simple solution is to add ng-change event on the input and then write a function which takes selectedFood as param and do the following:

  1. Iterates through foodList and changes every value to false
  2. Toggle status of selectedFood (if true set false end vice versa)

Something like this:

$scope.toggleParam = function(selectedFood){
    loopThroughAndSetToFalse();
    findAndSetReverseValue(selectedFood);
}
function loopThroughAndSetToFalse(){
  for(var i=0; i<$scope.foodList.length; i++){
    $scope.foodList[i].selected = false;
  }
}
function findAndSetReverseValue(selectedFood){
  for(var i=0; i<$scope.foodList.length; i++){
    if($scope.foodList[i].name === selectedFood.name){
        $scope.foodList[i].selected = !(selectedFood.selected);
    }
  }
}

And your html now will look like this:

<div ng-app="myapp" ng-controller="myController">
  <div ng-repeat="food in foodList">
   <span>{{food.name}}</span>
   <input type="radio" ng-model="food.selected" name="radiofood" ng-change="toggleParam(food)"  ng-value="true">
  </div>
  <br><br>
  {{foodList[0]}}<br>
  {{foodList[1]}}<br>
  {{foodList[2]}}
</div>

Upvotes: 0

Ankit Pundhir
Ankit Pundhir

Reputation: 1095

Add method to controller file:

$scope.selectFood = function(selectedFood){
    angular.forEach($scope.foodList,function(food){
        if(food != selectedFood){
            food.selected = false;
        }
    })
};

and add ng-change="selectFood(food)" to radio button.

Upvotes: 2

Related Questions