如何使单选按钮值只推入一次数组?

时间:2016-12-15 17:38:14

标签: javascript angularjs

My plunker

如何使单选按钮值只推入一次数组?

我的代码

$scope.toggleSelection = function(clickedItem) {
    var value = clickedItem;
      var index = $scope.selected_ingrediants.indexOf(value);
      if (index === -1) {
        $scope.selected_ingrediants.push(value);
      } else {
        $scope.selected_ingrediants.splice(index, 1);
      }

  } 

2 个答案:

答案 0 :(得分:0)

问题在于,只要单击单选按钮,就会按下无线电值。

ng-click="toggleSelection(get_ing_n)"

正确的方法是仅在单击提交按钮时推送值,而不是通过ng-click获取值,您应该使用ng-value,如AngularJS文档中所示:{{3} }

答案 1 :(得分:0)

这里是plunk

你需要告诉toggleSelection函数选择是一个无线电还是一个checkbok并相应地处理

<强>控制器

$scope.toggleSelection = function(clickedItem, selectOne) {
var value = clickedItem;

if(selectOne){
  var existing = $scope.selected_ingrediants.filter(function(ing){
    return ing.ingredientTypeId === value.ingredientTypeId;
  })[0];
  var hasSelectionIdx = $scope.selected_ingrediants.indexOf(existing);
  if (hasSelectionIdx === -1) {
    $scope.selected_ingrediants.push(value);
  } else {
    $scope.selected_ingrediants.splice(hasSelectionIdx, 1, value);
  }
}else{
  var hasIngredientIdx = $scope.selected_ingrediants.indexOf(value);
  if (hasIngredientIdx === -1) {
    $scope.selected_ingrediants.push(value);
  } else {
    $scope.selected_ingrediants.splice(hasIngredientIdx, 1);
  }
}
}

<强> HTML

<div ng-repeat="get_ingredientTypeName_values in get_ing_value.ingredientTypeList">
  {{get_ingredientTypeName_values.ingredientTypeName}}

   <div >
  <ul ng-show="get_ingredientTypeName_values.minVal == 1" ng-repeat="get_ing_n in get_ingredientTypeName_values.ingredientList">
    <li> <input type="radio" name="{{get_ing_n.ingredientTypeId}}" ng-click="toggleSelection(get_ing_n, true)">{{get_ing_n.ingredientName}},{{get_ing_n.ingredientPrice}}</li>
  </ul>
  </div>

  <div >
  <ul ng-show="get_ingredientTypeName_values.minVal == null" ng-repeat="get_ing_n in get_ingredientTypeName_values.ingredientList">
    <li> <input type="checkbox" name="{{get_ing_n.ingredientTypeId}}" ng-click="toggleSelection(get_ing_n, false)">{{get_ing_n.ingredientName}},{{get_ing_n.ingredientPrice}}</li>
  </ul>
  </div>

</div>