【问题标题】:Why does radio button with ng-repeat not work?为什么带有 ng-repeat 的单选按钮不起作用?
【发布时间】:2016-01-03 18:38:36
【问题描述】:

我有一个简单的 ng-repeat,带有一个无法正常工作的单选按钮。以下工作非常好:

<label class="radio-inline">
    <input type="radio" ng-model="display_as"  name="display_as" value="1">position 1
    <input type="radio" ng-model="display_as"  name="display_as" value="2">position 2
</label>
<pre>{{ display_as }}</pre>

但通过以下内容,我确实看到了两个单选按钮(如预期的那样),我可以选择两个单选按钮中的任何一个,但 $scope.display_as 仍未定义。

<label ng-repeat="position in user.positions" class="radio-inline">
    <input type="radio" ng-model="display_as"  name="display_as" value="{{ $index }}">{{ position.name }}
</label>
<pre>{{ display_as }}</pre>

为什么哦为什么?!有人可以告诉我我在ng-repeat 中做错了什么吗?

【问题讨论】:

  • 对于一些谜团,如果您使用 user.display_as,它可以工作 (jsbin.com/yaseye/edit?html,js,output)。优秀的@andrei-gheorghiu,过去我也遇到过同样的问题,我只使用 ng-change 解决了这个问题。

标签: javascript html angularjs


【解决方案1】:

ng-repeat 为通过user.positions 的每次迭代创建一个单独的子$scope。这些$scopes 都没有display_as 属性。

您可以使用$parent 访问ng-repeat 中的父$scope。在你的情况下:$parent.display_as

【讨论】:

    猜你喜欢
    • 2016-08-06
    • 1970-01-01
    • 2017-04-16
    • 2013-08-14
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2021-01-26
    • 2022-11-11
    相关资源
    最近更新 更多