gpt4 book ai didi

javascript - Angularjs 无法将单选按钮与嵌套范围内的模型绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 16:04:18 25 4
gpt4 key购买 nike

我有一个场景,我无法将单选按钮与我的模型绑定(bind)。在我的代码中,单选按钮是在 ng-repeat 中动态创建的,它位于 ng-if 中。这是我的代码

 <div ng-if="Type.Value == 'Gadgets'">
<div class="form-group radioChkBtn">
<label class="col-sm-3 control-label">Device Type</label>
<div class="col-sm-7">
<div class="radio" ng-repeat="type in Types">
<input type="radio" ng-model="DeviceType" ng-value="{{type.Value}}" id="radioDeviceType{{$index}}" name="devicetype"><label for="radioDeviceType{{$index}}"> {{type.Value}}</label>
</div>

</div>
</div>

DeviceType 的值始终未定义。即使我为其分配某个值,也没有选择任何单选按钮。ng-if 创建一个范围,ng-repeat 也是如此。可能是导致问题的范围嵌套。任何帮助将不胜感激。

最佳答案

相反,请尝试在单选选择上设置模型。

在你的 Controller 中有这个:

$scope.onRadioChange = function(newValue) {
$scope.DeviceType.value = newValue;
};

并使您的 HTML 类似于:

<div class="radio" ng-repeat="type in Types">
<input type="radio" ng-model="DeviceType.value" ng-change="onRadioChange(type.Value)" ng-value="type.Value" id="{{type.Id}}" name="myRadios"><label for="{{type.Id}}"> {{type.Value}}</label>
</div>

所以为了分解它,我们现在在通过 ng-change 单击单选按钮时触发范围函数 onRadioChange()。我们将 type.value 传递给它,并在函数内部使 DeviceType.value 的模型等于传递给它的值。

在下面的示例中,您可以看到我在单击单选按钮后在页面上输出了 DeviceType.value,并且它与选中的单选按钮具有相同的值。我使用 DeviceType.value 而不是仅仅使用 DeviceType 来解决 Angular 问题。

WORKING EXAMPLE

关于javascript - Angularjs 无法将单选按钮与嵌套范围内的模型绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37265156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com