这是我的用例
在我的HTML页面中,我有两组单选按钮:标签:" PRESENT"和"缺乏" / Values:分别为True和False。
最初我想将状态设置为" PRESENT"在所有公司。
如果我在表格的标题中设置了ABSENT单选按钮,它将在所有公司中将状态更新为“不存在”,并且也可以在个人中工作
这是我的剧本
<script>
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.companies = [{
"id": 4,
"name": "Facebook"
}, {
"id": 3,
"name": "Twitter"
}, {
"id": 2,
"name": "Google"
}, {
"id": 1,
"name": "Apple"
}]
$scope.userChoice = {};
}]);
</script>
我的html页面是
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<table>
<tr>
<th>#</th>
<th>Name</th>
<th><input type="radio" ng-model="allPresent" name="company" value="{{company.id}}" />Present</th>
<th><input type="radio" ng-model="allAbsent" name="company" value="{{company.id}}" />Absent</th>
</tr>
<tr ng-repeat="company in companies">
<td>{{$index+1}}</td>
<td>{{company.name}}</td>
<td><input type="radio" ng-model="userChoice.companyIdPresent" name="companyId" value="{{company.id}}" /></td>
<td><input type="radio" ng-model="userChoice.companyIdAbsent" name="companyId" value="{{company.id}}" /></td>
</tr>
</table>
<br>
<br>
<br>CompanyId is: {{userChoice.companyId}}
<br>
<br>
<button ng-disabled="!userChoice.companyId">Continue</button>
</div>
</div>
我想在所有公司中将状态设置为PRESENT
我的预期输出是
$scope.userChoice = [{
"companyId": 4,
"status": "PRESENT"
}, {
"id": 3,
"status": "ABSENT"
}, {
"id": 2,
"status": "ABSENT"
}, {
"id": 1,
"status": "PRESENT"
}]
你可以帮我设置一下这个场景吗?
答案 0 :(得分:1)
在您的代码中有几个问题
单选按钮组应使用相同的ng-model
。当ng-model
值等于name
值时,将选中此单选按钮。因此,您的第一对Present
和Absent
有ng-model
- $scope.all
,默认值为'allPresent'
关于ng-repeat:我们有4组,每组2个。所以我们需要创建4个不同的ng-model
。所以我们写道:ng-model="company.selected"
其中selected
值为true
或false
。出于这个原因,我们在ng-value
true
和false
取消/选择我们使用的所有无线电ng-change="onSelect(false)"
和ng-change="onSelect(true)"
将在所有群组上运行并将selected
从/更改为/ true
所以我发布了工作示例。
HTML 的
<table>
<tr>
<th>#</th>
<th>Name</th>
<th><input type="radio" ng-model="all" name="all" value="allPresent" ng-change="onSelect(true)" />Present</th>
<th><input type="radio" ng-model="all" name="all" value="allAbsent" ng-change="onSelect(false)"/>Absent</th>
</tr>
<tr ng-repeat="company in companies">
<td>{{$index+1}}</td>
<td>{{company.name}}</td>
<td><input type="radio" ng-model="company.selected" name="{{company.name}}" ng-value="true" /></td>
<td><input type="radio" ng-model="company.selected" name="{{company.name}}" ng-value="false" /></td>
</tr>
</table>
JS
$scope.companies = [{
"id": 4,
"name": "Facebook",
"selected": true
}, {
"id": 3,
"name": "Twitter",
"selected": true
}, {
"id": 2,
"name": "Google",
"selected": true
}, {
"id": 1,
"name": "Apple",
"selected": true
}];
$scope.userChoice = {};
$scope.all = 'allPresent';
$scope.onSelect = function(val){
angular.forEach($scope.companies, function(value){
value.selected = val;
})
}