1

When my form, with ng-submit="createNewOrder()", is submitted I call a resource service that performs some server-side validation. However, the form fields are cleared after the service returns. How to I prevent Angular from clearing the fields until the resource service returns a response that indicates success?

Edit: adding the code

HTML:

<div ng-app="OrdersApp" ng-controller="OrdersController" class="ng-scope">
  <form name="newOrderForm" ng-submit="createNewOrder();" novalidation>
    <label>First Name</label>
    <input type="text" ng-model="newOrder.firstName" required>
    <label>Last Name</label>
    <input type="text" ng-model="newOrder.lastName" required>
    etc.
  </form>
</div>

App:

var app = angular.module('OrdersApp', ['orderServices']);

Controller:

app.controller('OrdersController', function ($scope, Order) {
  $scope.newOrder = new Order({ });
  $scope.createNewOrder = function () {
    $scope.newOrder.$create(
      function(successData) {
        if (successData.error) return alert('order was not saved successfully');
        alert('order successfully charged and created');
      },
      function(errorData) { 
        alert('order was not saved successfully: ' + JSON.stringify(errorData));
      }
    );
  };
});

Services:

angular.module('orderServices', ['ngResource']).
  factory('Order', function ($resource) {
    return $resource('/admin/json/orders', {},
      {
        query: { method: 'GET', params: { }, isArray: true },
        create: { method: 'POST', params: { } },
        save: { method: 'PUT', params: { } }
      });
  });
motormal
  • 158
  • 1
  • 11
  • write the code, i have a form too and nothing went clear, so maybe it's an error in the code. – mautrok Apr 02 '14 at 13:00
  • See this answer- http://stackoverflow.com/questions/16153313/saving-new-models-using-angularjs-and-resource/33991999#33991999 – vivex Nov 30 '15 at 05:34

2 Answers2

1

My issue was that I'm calling:

$scope.newOrder.$create(...)

This will cause the $scope.newOrder object to be overwritten with the JSON object that is returned by the create method of the resource service. This then clears all the form fields because I'm returned a error object.

Changing this to:

Order.create($scope.newOrder, ...)

fixes the issue.

I could also have changed the resource service to return a non-200 HTTP status code and I believe my object wouldn't have been overwritten.

Hope that helps anyone out there with a similar issue.

motormal
  • 158
  • 1
  • 11
  • https://docs.angularjs.org/api/ngResource/service/$resource it says there is no create method, only save is there. – vivex Nov 30 '15 at 05:24
0

I think you are submitting the form. Instead of doing that, make a ajax call to send data to the server. I think it will work.

glepretre
  • 8,154
  • 5
  • 43
  • 57
Ranjit
  • 11
  • 1