问题
I'm creating radio buttons with ng-repeat and would like the selected button's name value to appear below.
Here is my view:
<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>
Here is my controller:
$scope.weights = [
{
name: 1,
checked: true
},
{
name: 2,
checked: false
},
{
name: 3,
checked: false
}
];
Here is my Plunker.
How can I get the weight to appear in the paragraph tag?
回答1:
You should maintain value of radio in one of the ng-model
& use $parent. to define it in controller scope rather than in ng-repeat
like here
Markup
<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>
Working Plunkr
回答2:
The answer lies in understanding how $scope works in angular. The quick solution is to use $parent.selectedName, where $parent refers to the parent scope. This is because each iteration of ng-repeat creates a scope of itself. (see enter link description here
See this https://jsfiddle.net/pankaj01/Xsk5X/3074/ the JS is
function MyCtrl($scope) {
$scope.weights = [
{
name: 1,
checked: true
},
{
name: 2,
checked: false
},
{
name: 3,
checked: false
}
];
}
来源:https://stackoverflow.com/questions/29750708/angularjs-radio-buttons-ng-repeat-value