AngularJS 单选按钮 ng-repeat 值

AngularJS radio buttons ng-repeat value

我正在使用 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
  }
];

Here is my Plunker.

如何让权重出现在段落标签中?

您应该在 ng-model 之一中保持无线电的价值并使用 $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>

Working Plunkr

答案在于了解 $scope 在 angular 中的工作原理。 快速解决方案是使用 $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
  }
];

}