Reputation: 178
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: { } }
});
});
Upvotes: 1
Views: 1440
Reputation: 11
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.
Upvotes: 0
Reputation: 178
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.
Upvotes: 1