2017-01-16 71 views
0

验证完我的表单后,我需要提交它。AngularJS验证我的表单

我需要将表单提交给另一个模拟API端点,根据提供的答案是否正确返回true或false,并在UI中显示此响应。

是否可以实现这个来存档它? https://docs.angularjs.org/api/ng/service/ $ HTTP

Plunker Demo

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 ng-if="field.type != 'radio'" ng-required="{{field.required}}" value="{{options.value}}" type="{{field.type}}"> 

      <div ng-if="field.type == 'radio'"> 
      <div ng-repeat="option in field.options"> 
       <input type="{{field.type}}" 
        ng-model="richestClub" 
        value="{{option.value}}">{{option.label}}</br> 
      </div> 

      </div> 



      <form-error ng-show="{{!!field.errorMessages.required}}">{{field.errorMessages.required}}</form-error> 
      <form-error ng-show="{{!!field.errorMessages.invalid}}">{{field.errorMessages.invalid}}</form-error> 
     </div> 
     </fieldset> 

     <button type="button" ng-click="onValidate(); return false;"> Validate</button> 
     <button type="submit" ng-disabled="userForm.$invalid"> 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); 
    }); 



    $http.get('form.json').success(function(response) { 
    $scope.result = response; 
    var fields = response.fields; 
    $scope.richestClub = fields.answer.options[0].value; 
    console.log($scope.richestClub); 
    console.log($scope.fields); 
    }); 

}); 

回答

0

这是绝对有可能的。但是,您的代码有几个错误。

您使用userForm作为表单变量,但不指定它。它应该像

<form name="userForm"> 

为了在JS中访问它。

相同的字段 - 如果你想访问他们的错误,你应该提供他们的名字 像<input type="" name="{{field.name}}" />然后你可以通过“userForm [field.name]”来访问验证结果。

添加回调提交按钮:<button type="submit" ng-disabled="userForm.$invalid" ng-click="onSubmit(userForm)"> Submit </button>

+0

不错的一个,你能提供一个plunker请与嘲笑API终点? – user3699998

+0

用你的建议检查这一个http://plnkr.co/edit/fK6NL8G6zgaTp7d4zM4P?p=preview – user3699998