javascript - Angular JS 在 radio 检查时显示输入

标签 javascript html angularjs ng-show

我有一个像这样的 JavaScript 数组:

$scope.quantityMachines = [
  { 'snippet' : 'One' },
  { 'snippet' : 'Two' },
  { 'snippet' : 'Three or more',
    'extraField' : true },
  { 'snippet' : 'Not sure, need advice' }
];

然后我有一个由 Angular JS 使用数组生成的单选按钮列表:

<ul>
  <li ng-repeat="quantity in quantityMachines">
    <input type="radio" id="quantityMachines{{$index}}" name="quantityMachines" value="{{quantity.snippet}}" ng-model="howMany" />
    <label for="quantityMachines{{$index}}">{{quantity.snippet}}</label>
  </li>
</ul>

这有效。在数组中,索引之一中有一个值为 trueextraField。当选中带有 extraField 设置的单选按钮时,我需要 Angular 显示额外的输入字段。该数组可能会更改为具有多个带有 extraField 值的索引。

所以额外的字段看起来像这样。

<input type="text" ng-model="extraInfo" ng-show="howMany" />

除了知道使用 ng-show 之外,我不确定执行此操作的正确方法是什么。上面的例子当然什么也没做。

最佳答案

您可以使用 ng-ifng-show 组合以及作用域变量来跟踪所选内容。 ng-if 将确保文本框不会被不必要地添加到 DOM 中,并且 ng-show 将在单选按钮切换时显示和隐藏。

在您的输入中:-

<input type="text" ng-model="extraInfo" ng-if="quantity.extraField" ng-show="option.selected === howMany" />

并在您的Radio中添加ng-click="option.selected=quantity.snippet"

<ul>
  <li ng-repeat="quantity in quantityMachines">
    <input type="radio" id="quantityMachines{{$index}}" name="quantityMachines" value="{{quantity.snippet}}" ng-model="howMany" ng-click="option.selected=quantity.snippet"/>
    <label for="quantityMachines{{$index}}">{{quantity.snippet}}</label>
    <input type="text" ng-model="extraInfo" ng-if="quantity.extraField" ng-show="option.selected === howMany" />
  </li>
</ul>

并添加到您的 Controller 中:-

$scope.option = { selected:'none'};

<强> Bin

您甚至可以使用 howMany 来跟踪选择的内容,只不过您需要将其设置为作用域上对象的属性(因为 ng-repeat 创建了自己的子作用域并且原型(prototype)继承来了玩)。

因此,在您的 radio 中只需添加 ng-model="option.howMany",在 Controller 中添加 $scope.option = { }; 并在文本框中添加ng-if="quantity.extraField"ng-show="quantity.snippet === option.howMany"

<强> Bin

关于javascript - Angular JS 在 radio 检查时显示输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25047867/

相关文章:

javascript - 通过 angularjs ng-repeat 传递 href 链接

javascript - 类型错误 : Cannot read property 'nombre' of undefined

javascript - 是否可以在 Javascript 的选择选项上附加商品数量?

javascript - 如何在事件中或手动启动 CKeditor 插件?

javascript - 将数据从 JavaScript 发送到本地 Python

javascript - 未处理的拒绝(类型错误): Cannot read property of undefined

angularjs - Freemarker 与 AngularJS

html - CSS 中可见性和显示的优先顺序

javascript - 使用 JavaScript 旋转图标无法正常工作

php - 在 Wordpress 中,如何根据用户所在的页面更改链接的目标?