以下是我的代码,其中我没有为每个相应的行选择单选选项,让我知道我在这里做错了什么。
我的 Plnkr 代码 - http://plnkr.co/edit/MNLOxKqrlN5ccaUs5gpT?p=preview
虽然我得到了 classes
对象的名称,但没有得到选择。
HTML代码-
<body ng-controller="myCtrl">
<div class="container-fluid">
<form name="formValidate" ng-submit="submitForm()" novalidate="" class="form-validate form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" required="" ng-model="classes.name" class="form-control" />
</div>
</div>
<div class="form-group">
<table id="datatable1" class="table table-striped table-hover">
<tr class="gradeA" ng-repeat="cls in reqgrps">
<td ng-bind="cls.name"></td>
<td><input type="radio" name="groupName[{{$index}}]" ng-model="classes.satisfies"> Choice 1</td>
<td><input type="radio" name="groupName[{{$index}}]" ng-model="classes.satisfies"> Choice 2</td>
<td><input type="radio" name="groupName[{{$index}}]" ng-model="classes.satisfies"> Choice 3</td>
</tr>
</table>
</div>
<div class="panel-footer text-center">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</form>
</div>
<div class="result">{{classes}}</div>
</body>
脚本文件-
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope){
$scope.reqgrps = [{name: 'Sub1', roll: 121},{name: 'Sub2', roll: 122}, {name: 'Sub3', roll: 123}];
$scope.classes = {};
$scope.result = {};
$scope.submitForm = function() {
$scope.result = $scope.classes;
};
});
------------编辑------------
预期输出-
类对象 -
{
name: "Test Class",
satisfies: [
"Sub1": "Choice 1",
"Sub2": "Choice 3",
"Sub3": "Choice 2",
.................
..................
..................
..................
"Subn": "Choice 2",
]
}
最佳答案
您需要区分 ng-repeat 生成的每一行。
您可以像这样向每个 ng-model 添加 [$index] 来做到这一点:
<td><input type="radio" ng-model="classes.satisfies[$index]" value="Choice 1"> Choice 1</td>
<td><input type="radio" ng-model="classes.satisfies[$index]" value="Choice 2"> Choice 2</td>
<td><input type="radio" ng-model="classes.satisfies[$index]" value="Choice 3"> Choice 3</td>
正如其他人所提到的,您可以通过使用 ng-value 设置传递到模型中的值来根据需要使结果动态化。
生成的对象是这样的:
{"name":"Bill","satisfies":{"0":"Choice 2","1":"Choice 1","2":"Choice 3"}}
关于javascript - 无法在 AngularJS 中动态获取 radio 选择设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30468122/