我有2个性别单选按钮。
<input type="radio" name="answer" value="Female" ng-model="$parent.gender" />Female
<input type="radio" name="answer" value="Male" ng-model="$parent.gender" />Male
我想要显示预先选择的表格。我在控制器中的数组中有这样的答案:
$scope.answers={gender:"Female"};
对于此示例,如何根据答案对象设置女性单选按钮?提前致谢
答案 0 :(得分:2)
并提出了性别范围变量。这是 DEMO
和代码段:
<强> HTML:强>
<div ng-app>
<div ng-controller="test">
<input type="radio" name="answer" value="Female" ng-model="answers.gender" />Female
<input type="radio" name="answer" value="Male" ng-model="answers.gender" />Male
</div>
</div>
<强>控制器:强>
function test($scope){
$scope.answers={gender:"Female"};
}
答案 1 :(得分:1)
设置您声明为模型的gender
变量:
ng-model="$parent.gender"
因此,设置$scope.gender = "Female"
以选择该无线电。
答案 2 :(得分:1)
如果您不在儿童范围内(ala ng-repeat),您不需要$ parent:
app.controller('MainCtrl', function($scope) {
$scope.answers = { gender: 'Female' };
});
HTML
<div ng-controller="MainCtrl">
<input type="radio" value="Female" ng-model="answers.gender"/>
<input type="radio" value="Male" ng-model="answers.gender"/>
</div>
鉴于您的示例显示ng-model="$parent.gender"
,看起来您认为需要从父作用域获取性别,这在ng-repeat中才真正有必要,这会创建子作用域。当您使用转发器创建单选按钮列表时,您可能会发现这一点:
JS:
app.controller('MainCtrl', function($scope) {
$scope.radioItems = ['Male', 'Female', 'Other'];
$scope.answers = {
gender: 'Female',
};
});
HTML:
<div ng-repeat="radioItem in radioItems">
<input type="radio" value="radioItem" ng-model="$parent.answers.gender"/>
</div>