【问题标题】:Broken ngModel on Radio buttons with an ngRepeat带有 ngRepeat 的单选按钮上的 ngModel 损坏
【发布时间】:2014-08-27 08:47:48
【问题描述】:

Plunk:http://plnkr.co/edit/Y4ntAj2fIIpexKjkCvlD?p=preview

我正在尝试构建一个表单组件,它允许用户创建某个数据字段的多个实例,但从同一组输入中填充它们。

我正在为集合中的每个项目创建一个单选按钮,使用 ng-repeat 然后每个单选按钮的值设置为重复中的 $index。单选按钮以$scope.selectedItem 为模型,用于将输入指向正确的项目。

然而,由于某种原因,selectedItem 永远不会改变,即使单选按钮的选中状态会改变。

我用静态单选按钮尝试了类似的操作,效果很好,这让我相信ng-modelng-repeat 中存在问题。

【问题讨论】:

    标签: javascript angularjs angularjs-ng-repeat angular-ngmodel


    【解决方案1】:

    您需要为每个按钮添加ngModel。然后,由于ngRepeat 的每次迭代都会创建一个新的隔离范围,因此您有两种方法可以在父控制器中引用您的变量:

    1. selectedItem 更改为一个对象。这是可行的,因为对象在 JS 中是通过引用传递的,而传递像您这样的原语不适用于双向绑定。

    2. 添加$parent.selectedItem,它引用控制器中的范围变量selectedItem

    无论如何,每个按钮都需要ngModel

    第一个选项:

    <input type='radio' 
           name='select' 
           id='{{$index}}' 
           ng-value='$index' 
           ng-model='$parent.selectedItem'/>
    

    Plunker Using $parent

    第二个选项:

    JS:

    $scope.selectedItem = {id: -1};
    

    HTML:

    <input type='radio' 
           name='select' 
           id='{{$index}}' 
           ng-value='$index' 
           ng-model='selectedItem.id'/>
    

    (以及将您引用 selectedItem 的其他任何地方更改为 selectedItem.id

    Plunker Using an object for selectedItem

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2016-10-20
    • 2012-03-05
    • 2013-10-06
    • 2021-04-02
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多