Angular5表格单选按钮无法提交布尔值,需双击才能提交对应值
It looks like the core problem here is that you're concatenating the row identifier (k) with the boolean value in your radio button's value attribute. Every time you click a radio button, the model gets updated to that concatenated string (e.g., k+false), and then the next click uses that already modified value to concatenate again—leading to the repeated k+k+false pattern you're seeing.
Here's how to fix this:
1. Separate Row Identification from Selection Value
Don't include the row key (k) in the radio button's value. Instead, use the value to hold just the boolean (true/false), and pass the row identifier to your onSelectionChange method explicitly.
For example, if you're using AngularJS (common for this template syntax), your radio buttons might look like this:
<!-- For each row with key {{k}} --> <div class="row"> <label> <input type="radio" name="selection-{{k}}" value="true" ng-model="selectedState[k]" ng-change="onSelectionChange(k, true)"> Select </label> <label> <input type="radio" name="selection-{{k}}" value="false" ng-model="selectedState[k]" ng-change="onSelectionChange(k, false)"> Deselect </label> </div>
- The
nameattribute usesselection-{{k}}to group radio buttons per row, ensuring only one can be selected per row. - The
valueis justtrueorfalse, no concatenated strings. selectedState[k]tracks the current selection for each row (initialize this as an object in your controller to hold boolean values for eachk).
2. Update onSelectionChange to Set Boolean Values Directly
Modify your method to take the row key and selected boolean value, then update your submission object with just the boolean—no concatenation needed:
// In your controller $scope.selectedState = {}; // Initialize with default values if required $scope.submissionObject = {}; // Your object to submit $scope.onSelectionChange = function(rowKey, isSelected) { // Update the submission object with the pure boolean value $scope.submissionObject[rowKey] = isSelected; // Optional: Verify the correct value is set console.log(`Row ${rowKey} selected: ${isSelected}`); };
Why This Works
By separating the row identifier from the selection value, you eliminate the recursive concatenation issue. Each click directly sets the boolean state for the specific row, and your submission object will have clean true/false values mapped to each row key.
If you're using a different framework (like Vue or React), the core logic stays the same: keep the radio button value as a pure boolean, use the row key to target the correct entry in your submission object, and update it directly with the boolean value.
内容的提问来源于stack exchange,提问作者Nitin Bhargava

