I am working with a somewhat dynamic AngularJS form. In other words, I am able to add rows of input fields, etc. So my approach was to start with a $scope.formData
empty object, to encapsulate all the properties that are bound to both static and dynamic HTML form elements.
The AngularJS code is as follows:
(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
$scope.formData = {};
$scope.formData.subscribers = [
{ name: null, email: null }
];
$scope.addSubscriber = function() {
$scope.formData.subscribers.push({ name: null, email: null });
};
});
})();
The HTML for the AngularJS form:
<body data-ng-app="formApp">
<div data-ng-controller="FormCtrl">
<p>
Name of Topic: <input type="text" data-ng-model="formData.title" placeholder="enter a title" />
</p>
Subscribers:
<button data-ng-click="addSubscriber()">Add subscriber</button>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr data-ng-repeat="subscriber in formData.subscribers">
<td><input type="text" data-ng-model="subscriber.name" placeholder="enter name" /></td>
<td><input type="text" data-ng-model="subscriber.email" placeholder="enter email" /></td>
</tr>
</table>
<hr style="margin:1em 0;" />
<p>
<em>Debug info</em>: {{ formData }}
</p>
</div>
</body>
Note the Debug info section at the end, which displays the $scope.formData
object and its contents. I have a couple of issues with the way I have implemented this form.
- When the page first loads, there is no
formData.title
property in the$scope
, but since it is bound to the Title input text field, when I start typing a value, thetitle
property gets added to the$scope
. However when I delete the value in the input text field, theformData.title
property still exists in the$scope
as an empty string. I suppose this is okay, but I really want to clean up empty or null values when submitting the form. I would like to do it on the client side if it is easy to do so, so the server side code does not have to clean up anything. - With the dynamic Subscribers section, I can keep adding as many rows as I want, but ultimately, I would like to filter out all empty subscriber objects on the client side.
Does AngularJS have any options for detecting and cleaning null/empty values in the $scope
before further processing, such as a $http
POST?
Note I have set up a jsFiddle for this example.