Javascript 在ng repeat中使用单选按钮,角度

Javascript 在ng repeat中使用单选按钮,角度,javascript,angularjs,Javascript,Angularjs,我有一个带有选项的数组,我希望用户能够在其中选择一个选项 以下是我的选择: $scope.licenses = [...] 这是所选的选项: $scope.selectedLicense = $scope.licenses[0]; 在我的标记中,我有: <ul> <li ng-repeat="lic in licenses"> <input type="radio" ng-model="selectedLice

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

以下是我的选择:

 $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>
  • {{lic.nroflices}
但在开始时没有选择单选按钮

小提琴:


我做错了什么?

您需要使用ng value指令而不是value,这允许您使用范围对象

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


ng repeat
指令中,为每次迭代创建子范围

检查

每个模板实例都有自己的作用域

因此,重复时,每个子作用域中都有一个称为
selectedLicense
的作用域变量。因此,您的
$scope.selectedLicense
不会像预期的那样绑定到
单选按钮

在这里你可以使用原型继承,这是一个很好的答案


以下是

如何获得模型值?
$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.
$scope.x = {};
$scope.x.selectedLicense = $scope.licenses[0];

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