AngularJS ng-repeat下使用ng-model

1
2
3
blue:<input type="radio" value="1" ng-model="selectValue"/>
red:<input type="radio" value="2" ng-model="selectValue"/>
yellow: <input type="radio" value="3" ng-model="selectValue"/>

以上代码实现一个单选框功能,当你选中其中的一个单选框,能够从$scope.selectValue中获得你选中的的选项的value。
同时改变$scope.selectValue的值,也能够让界面上选中相应的单选框。html

假设单选框的个数是不固定的,用ng-repeat来展示。code

1
2
3
4
5
6
7
<table>
<tr ng-repeat="row in collections">
<td>
{{row.name}}: <input type="radio" value="{{row.value}}" ng-model="selectValue"/>
</td>
</tr>
</table>

当你书写了上述代码后。你会发现点击其中的对话框,$scope.selectValue中并无保存你选中的对应单选框的值。htm

这是由于处在ng-repeat之间的代码,对全局的$scope里变量的内容是不可见的,像{{row.name}}里的row,并非全局$scope里的成员。
而是为ng-repeat建立的子scope里面的。因此要引用全局$scope里的成员,你能够使用$parent 来引用全局的$scopeinput

1
2
3
4
5
6
7
<table>
<tr ng-repeat="row in collections">
<td>
{{row.name}}: <input type="radio" value="{{row.value}}" ng-model="$parent.selectValue"/>
</td>
</tr>
</table>
相关文章
相关标签/搜索