我正在使用ng-repeat创建单选按钮,并希望所选按钮的名称值显示在下方。
以下是我的观点:
<span ng-repeat="weight in weights">
<input type="radio" name="weight" value="{{weight.name}}" id="weight{{weight.name}}" ng-checked="weight.checked">
<label for="weight{{weight.name}}">{{weight.name}}</label>
</span>
<p>Weight: {{weight.name}}</p>
这是我的控制器:
$scope.weights = [
{
name: 1,
checked: true
},
{
name: 2,
checked: false
},
{
name: 3,
checked: false
}
];
如何让权重显示在段落标记中?
答案 0 :(得分:2)
你应该在ng-model
&amp;之一中保持无线电的价值。使用$ parent。在控制器范围内定义它而不是像ng-repeat
这样的
<强>标记强>
<body ng-controller="MainCtrl" ng-init="radioValue=1">
<span ng-repeat="weight in weights">
<input type="radio" name="weight" ng-model="$parent.radioValue" ng-value="{{weight.name}}" id="weight{{weight.name}}" ng-checked="weight.checked">
<label for="weight{{weight.name}}">{{weight.name}}</label>
</span>
<p>Weight: {{radioValue}}</p>
</body>
答案 1 :(得分:0)
答案在于了解$ scope如何在角度中工作。 快速解决方案是使用$ parent.selectedName,其中$ parent指向父范围。这是因为ng-repeat的每次迭代都会创建其自身的作用域。 (请参见enter link description here
查看此https://jsfiddle.net/pankaj01/Xsk5X/3074/ JS是
function MyCtrl($scope) {
$scope.weights = [
{
name: 1,
checked: true
},
{
name: 2,
checked: false
},
{
name: 3,
checked: false
}
];
}