Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS form and null/empty values

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, the title property gets added to the $scope. However when I delete the value in the input text field, the formData.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.

like image 744
Web User Avatar asked Apr 19 '15 03:04

Web User


People also ask

Is null or empty in angular?

How to check if a variable string is empty or undefine or null in Angular. In template HTML component: We can use the ngIf directive to check empty null or undefined. In this example, if stringValue is empty or null, or undefined, It prints the empty message.

How check value is null in Angularjs?

You can use angular's function called angular. isUndefined(value) returns boolean. Show activity on this post. if(!a) { // do something when `a` is not undefined, null, ''. }

How check variable is empty or not in Angularjs?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


Video Answer


1 Answers

Simply use ngModelController $parsers and overwrite the default HTML input element.

With this implementation you can have control over the model value all the time. So in your case you can set the model to null whenever the view value is empty String.

var inputDefinition = function () {
return {
  restrict: 'E',
  require: '?ngModel',
  link: function (scope, element, attr, ngModel) {
    if (ngModel) {
      var convertToModel = function (value) {
        return value === '' ? null : value;
      };
      ngModel.$parsers.push(convertToModel);
    }
  }
};
/**
* Overwrite default input element.
*/
formApp.directive('input', inputDefinition);

Here is the updated JSFiddle: https://jsfiddle.net/9sjra07q/

like image 128
Tome Pejoski Avatar answered Oct 14 '22 10:10

Tome Pejoski