我通過遍歷具有不同問題的對象來向用戶進行迭代,從而在視圖中動態創建表單。每個問題的屬性之一是formFieldName
這是一個隨機字符串,我用它來給每個表單字段一個不同的名稱。以角度驗證具有動態給定名稱的表單域
<form name="includedForm.newRequestForm" class="form-horizontal" role="form" novalidate>
<div ng-if="message.question.attributes.structure.type == 'object'">
<div ng-repeat="(index,objField) in message.question.attributes.structure.properties">
<div ng-if="objField.type == 'array'" class="form-group" show-errors>
<label for="{{objField.formFieldName}}" class="control-label col-sm-6">{{objField.title}}
<br /><i><small>{{objField.description}}</small></i></label>
<div class="col-sm-6">
<select class="form-control" name="{{objField.formFieldName}}" multiple ng-model="objField.userValue" ng-required="objField.required">
<option ng-repeat="option in objField.items.enum" value="{{option}}">{{option}}</option>
</select>
</div>
</div>
<div ng-if="objField.type == 'boolean'" class="form-group" show-errors>
<label for="{{objField.formFieldName}}" class="control-label col-sm-6">{{objField.title}}</label>
<div class="col-sm-6">
<input class="form-control" name="{{objField.formFieldName}}" ng-model="objField.userValue" type="checkbox" ng-value="option" ng-checked="message.question.attributes" />
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<button ng-click="markAsDone(message)" class="btn btn-primary">Done</button>
</div>
<form>
在控制器中,我能夠獲得formFieldName屬性,但我無法弄清楚如何使用它來進行驗證。
var MarkAsDone = function(message) {
$scope.includedForm = {};
var formField = message.question.attributes.formFieldName;
if ($scope.includedForm.newRequestForm.{{formField}}.$valid){
//submit the form
}
}
如果'formField'實際上是字段的名稱,你應該能夠使用'如果($ scope.includedForm.newRequestForm [formField] $有效) { //提交表格 }'......必須使用括號表示法來訪問作爲屬性的變量。 –
我試過了,並且在開始ng-repeat之前(在表單元素中)錯誤:$ scope.includedForm.newRequestForm [formField]未定義' –
add'ng-init =「includedForm.newRequestForm = {}」' ) –