在 ng-repeat 中使用单选按钮,angular

Using radiobuttons in ng-repeat, angular

我有一个包含选项的数组,我希望用户能够在其中选择一个选项。

这是我的选择:

 $scope.licenses = [...]

这是选择的选项:

 $scope.selectedLicense = $scope.licenses[0];

在我的标记中我有:

    <ul>
        <li ng-repeat="lic in licenses">
            <input type="radio" ng-model="selectedLicense" value="lic"></input>
                {{lic.nrOfLicenses}}
        </li>
    </ul>

但是在开始时没有选择单选按钮。

小提琴:http://jsfiddle.net/HB7LU/9765/

我做错了什么?

您需要使用 ng-value 指令而不是值,这样您就可以使用范围对象。

<input type="radio" name="license" ng-model="selectedLicense" ng-value="lic"></input>

http://jsfiddle.net/2kqp2v46/

ng-repeat 指令中为每次迭代创建子作用域

勾选 documentation

Each template instance gets its own scope

所以当重复时,每个子作用域中都有一个名为 selectedLicense 的作用域变量。所以你的 $scope.selectedLicense 没有按预期绑定到 radio 按钮。

这里你可以使用原型继承,这里是什么是 JavaScript Prototypal Inheritance

的最佳答案
$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0].nrOfLicenses;

<input type="radio" ng-model="x.selectedLicense" ng-value="lic.nrOfLicenses"></input>
// here angular search the `selectedLicense` in the child scope and then it will search the x object in parent scope after it detect there is no `selectedLicense` in the child scope.

这里是 demo Fiddle


在上面的示例中,单选按钮绑定到对象中的 nrOfLicenses 属性。

如果要将 radio 绑定到整个对象,则按照此

$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0];

<input type="radio" ng-model="x.selectedLicense" ng-value="lic"></input>

这里是 demo Fiddle