我有一个像这样的 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>
这有效。在数组中,索引之一中有一个值为 true
的 extraField
。当选中带有 extraField
设置的单选按钮时,我需要 Angular 显示额外的输入字段。该数组可能会更改为具有多个带有 extraField
值的索引。
所以额外的字段看起来像这样。
<input type="text" ng-model="extraInfo" ng-show="howMany" />
除了知道使用 ng-show
之外,我不确定执行此操作的正确方法是什么。上面的例子当然什么也没做。
最佳答案
您可以使用 ng-if
和 ng-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/