当REST API调用失败时,如何在angular JS中重新填充用户输入的表单值

时间:2016-11-23 22:25:43

标签: angularjs rest api

我正在使用带有下拉列表和文本框的角度js表单,提交我打算调用REST API以保存用户输入值的表单。我想知道如果插入失败,如何重新填充用户在前端输入的表单值并显示错误消息

1 个答案:

答案 0 :(得分:0)

以下是制作副本并重新设置用户deets的一种方法。希望能帮助到你。以下代码为Codepen

function exampleFactory($http) {
  //placeholder exampleFactory 
  console.log('exampleFactory');

  function login() {
    return {
      data: console.log('data saved')
    };
  }
  return {
    login: login
  };
}

function exampleController($scope, exampleFactory, $timeout) {
  var copyOfUserDeets;
  $scope.userForm = {};
  $scope.submit = function(userDeets) {
    copyOfUserDeets = angular.copy(userDeets);
    $scope.userForm = {};
    // exampleFactory
    //     .login(userDeets)
    //     .then(function(resp) {
    //         $scope.userForm = {};
    //     })
    //     .catch(function(error) {
    //         $scope.userForm = copyOfUserDeets;
    //     });
    $timeout(function() {
      $scope.userForm = copyOfUserDeets;
    }, 10000);
  };
}

angular
  .module('app', [])
  .controller('exampleController', exampleController)
  .factory('exampleFactory', exampleFactory);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>

<div class="container-fluid text-center" ng-app="app">
  <div class="container text-center" ng-controller="exampleController">
    <form name="userLoginForm" ng-submit="submit(userForm)" ng-model="userForm" novalidate>
      <input type="email" name="email" ng-model="userForm.email" required="">
      <input type="text" name="password" ng-model="userForm.text" required="">
      <input type="submit" value="Submit" ng-disabled="userLoginForm.$invalid">
    </form>
    <pre>{{userForm}}</pre>
  </div>
</div>