I work with a somewhat dynamic form of AngularJS. In other words, I can add lines of input fields, etc. So my approach was to start with an empty $scope.formData in order to encapsulate all the properties bound to both static and dynamic elements of the HTML form.
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 }); }; }); })();
HTML for 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>
Notice the debugging information section at the end that displays the $scope.formData object and its contents. I have a couple of problems with how I implemented this form.
- When the first page loads,
$scope does not have the formData.title property, but since it is bound to the header text box, when I start typing in the value, the title property is added to $scope . However, when I delete the value in the input text field, the formData.title property still exists in $scope as an empty string. I suppose this is normal, but I really want to clear empty or null values ββwhen submitting the form. I would like to do this on the client side if this is easy to do, so server-side code should not take anything away. - In the dynamic subscribers section, I can add as many rows as I want, but ultimately, I would like to filter out all empty client objects on the client side.
Does AngularJS have any options for detecting and clearing null / empty values ββin $scope before further processing, for example, $http POST?
Note I set jsFiddle for this example.
javascript html angularjs angularjs-scope
Web user
source share