gpt4 book ai didi

javascript - Angular ng-repeat 与混合元素

转载 作者:行者123 更新时间:2023-11-29 10:35:26 24 4
gpt4 key购买 nike

我正在尝试将使用 .Net MVC 的表单转换为使用 Angular。我正在尝试使用 ng-repeat 在表单中生成输入字段。这是按预期工作的。但是,我需要将选择字段与文本输入字段混合在一起。

如何使用 ng-repeat 在一个表单中混合文本字段和选择字段?有可能吗?我也是 Angular 的新手。此代码只是一个非常简单的示例,将被清理并正确构建。

<div ng-app>
<div ng-init="profiles = [
{id: 'first-name', label: 'First Name', type: 'text'},
{id: 'middle-name', label: 'Middle Name', type: 'text'},
{id: 'last-name', label: 'Last Address', type: 'text'},
{id: 'suffix', label: 'Suffix', type: 'text'},
{id: 'social-security-number', label: 'Social Security Number', type: 'text'},
{id: 'DateOfBirth1', label: 'Date of Birth', class: 'datePicker hasDatepicker valid', type: 'text'},
{id: 'years-in-school', label: 'Years in School', type: 'text'},
{id: 'marital-status', label: 'Marital Status', type: 'select'}
]">
<h2>Borrowers Information</h2>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<div ng-repeat="profile in profiles" class="control-group col-md-3">
<label class="control-label" for="{{profile.id}}">{{profile.label}}</label>
<div class="controls">
<input data-val="true" data-val-required="Please enter a valid first name." id="{{profile.id}}" name="{{profile.id}}" value="" type="{{profile.type}}" class="{{profile.class}}">
</div>
</div>
</div>
</div>
<script>

最佳答案

您可以使用 Angular ng-switch 或 ng-if 作为类型,并将您的选择选项作为数组添加到您的表单对象中,如下所示:

https://jsfiddle.net/82u6gj26/

Angular

vm.person = {};
vm.form = [{
type:'text',
label:'First Name',
id:'first_name'
},
{
type:'select',
label:'Marital Status',
id:'marital_status',
options:[
{id:'Single',name:'Single'},
{id:'Married',name:'Married'}
]}
];

HTML

<div ng-repeat="form in ctrl.form">
<div class="form-group">
<label>{{form.label}}</label>
<div ng-switch="form.type">
<input
type="text"
ng-switch-when="text"
ng-model="ctrl.person[form.id]">

<select
ng-switch-when="select"
ng-model="ctrl.person[form.id]"
ng-options="s.id as s.name for s in form.options">
<option>Select One</option>
</select>
</div>
</div>
</div>

关于javascript - Angular ng-repeat 与混合元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37216385/

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