我的json中有一个条件是它的成分的最小值等于1意味着它将变为无线电,如果它大于1意味着将变为复选框..
将其显示为广播
ng-if="get_ingredientTypeName_values.minVal == 1"
<input id="{{get_option_names_price.ingredientTypeId}}_{{$index}}" name="{{get_option_names_price.ingredientTypeId}}" type="radio">
将其显示为复选框
ng-if="get_ingredientTypeName_values.minVal == null">
<input id="{{get_option_names_price.ingredientTypeId}}_{{$index}}" name="{{get_option_names_price.ingredientTypeId}}" type="checkbox">
如何获取两个值并保存到数组?
答案 0 :(得分:1)
I've updated your plunker to a working example
让我指导您解决问题所需的内容。如果已将可以选择的成分列表放入指令中,以便于扩展和可读性。
首先需要做的是确保将单个值呈现为单选按钮,将多个值呈现为复选框。为此我做了同样的检查:
// Check if the ingredients should be displayed as a radio button or a checkbox
scope.inputType = scope.ingredientType.minVal == 1 ? "radio" : "checkbox";
这允许我使用以下模板将这些成分渲染为单选按钮或复选框(暂时忽略ng-checked
和ng-click
):
<ul class="col-xs-12 form-group" ng-repeat="get_option_names_price in ingredientType.ingredientList ">
<li><input type="{{ inputType }}" ng-checked="valueIsSelected(get_option_names_price)" value="{{ get_option_names_price.productId }}" ng-click="toggleSelection(get_option_names_price)">{{get_option_names_price.ingredientName}}, $ {{get_option_names_price.ingredientPrice}}</li>
</ul>
下一步是跟踪代码中的选择。这非常棘手,因为在单选按钮的情况下我们可以简单地使用ng-model
但是为了支持复选框,我们需要跟踪代码中的选择。为此,我将成分上的属性引入了一个空数组,并且我已经通过单击单选按钮或复选框向该指令添加了一个函数(这就是模板包含ng-click
)的原因:
// Set the initial selection value. Because we need to have the possibility to select multiple values, this is an array
scope.ingredientType.selection = [];
// Function that is triggered by clicking an ingredient. The clicked item is passed to the function.
// If multiple values are allowed, a check is being made whether the item was already selected. This means we should remove it from the selection.
// If only one value is allowed, a single value array is set as the selection of the control.
scope.toggleSelection = function(clickedItem){
var value = clickedItem.ingredientName;
// Multiple values are allowed
if(scope.inputType === "checkbox"){
// Check if the clicked item exists in the selection
var index = scope.ingredientType.selection.indexOf(value);
// It doesn't exist
if(index === -1){
scope.ingredientType.selection.push(value);
} else {
// It already exists, so it should be removed
scope.ingredientType.selection.splice(index, 1);
}
} else {
// Only one value is allowed
scope.ingredientType.selection = [value];
}
}
最后,我们需要确保将所选值呈现给用户,以便他知道他选择了什么。这可以通过使用ng-check
指令并在我们自己的指令控制器中调用函数来实现:
// Function that checks whether an item is selected.
// This function is being used in the template to show the user whether he has selected an item or not.
// -> ng-checked
scope.valueIsSelected = function(item){
var value = item.ingredientName;
// Check if the clicked item exists in the selection
var index = scope.ingredientType.selection.indexOf(value);
return index > -1;
}
因为我们在配料中添加了一个属性,所以可以通过整个角度应用程序访问它,并且不需要有一个收集所选项目的按钮。