我正在尝试将表单提交到另一个模拟的API终结点,该终结点根据提供的答案是否正确而返回true或false。我是AngularJS的新手,我试图一点一点地掌握它。
HTML:
<my-form ng-app="CreateApp" ng-controller="mainController">
<form ng-submit="submitForm()" novalidate>
<fieldset>
<div ng-repeat="field in result.fields">
<label for="{{field.type}}">{{field.label}}</label>
<input type="{{field.type}}" ngRequired="{{field.required}}">
<span ng-show="{{field.errorMessages}}"></span>
</div>
<!-- not sure how to display the answers options and validate them -->
<input type="{{answer.type}}" name="{{answer.label}}" ngRequired="{{answer.required}}" />
</fieldset>
<button type="button" ng-click="onValidate(); return false;"> Validate</button>
<button type="submit"> Submit </button>
</form>
</my-form>
JS:
var myApp=angular.module('CreateApp', []);
myApp.controller('mainController', function($scope, $http) {
$http.get('form.json').success(function(response) {
$scope.result = response;
console.log($scope.fields);
});
// function to submit the form after all validation has occurred
$scope.submitForm = function() {
// check to make sure the form is completely valid
if ($scope.userForm.$valid) {
alert('our form is amazing');
}
};
});
只需对模板进行一些更新即可获得所需的结果。
ng-show
指令需要一个布尔值,因此您可以将消息的存在转换为布尔值,然后在范围内显示要在表达式为true时显示的文本。内部ng-repeat
用于循环选项并为每个选项创建一个新的字段集。如果没有可用的选项,那么我们将使用一个仅包含该字段的列表,就像我们对每个选项所做的那样,该字段使我们能够访问其标签和值信息。
<my-form ng-app="CreateApp" ng-controller="mainController">
<form ng-submit="submitForm()">
<fieldset>
<div ng-repeat="(key, field) in result.fields">
<div ng-repeat="option in ((field.type && field.options) || [field])">
<label for="{{field.type}}">{{option.label}}</label>
<input type="{{field.type}}" name="{{key}}" ngRequired="{{field.required}} value="{{option.value}}">
<span ng-show="{{!!field.errorMessages.required}}">{{field.errorMessages.required}}</span>
<span ng-show="{{!!field.errorMessages.invalid}}">{{field.errorMessages.invalid}}</span>
</div>
</div>
</fieldset>
<button type="button" ng-click="onValidate(); return;"> Validate</button>
<button type="submit"> Submit </button>
</form>
</my-form>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句