Dean Christian Armada Dean Christian Armada - 1 year ago 106
Javascript Question

Remove key-value if input is null in angularJS

I have a form with all inputs decleared as models like "ng-model = 'input.text' ". Everything works fine but what I need is whenever the value is now null the key-value pair should be gone as well like {} not { 'text':"" }. This can be achieved if the model is required but I was wondering if this is achievable without using required.

The code is:

<!DOCTYPE html>
<html ng-app="myApp">

<link rel="stylesheet" type="text/css" href="">
<script src=""></script>
<script src=""></script>

<body ng-controller="myCtrl">
<input type="text" ng-model="input.text">
<input type="number" ng-model="input.number">
<p>{{ input }}</p>
<script type="text/javascript">
app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout){
$scope.input = {};

The plunker is:


The JSON value of input will be passed to the server as a JSON object through HTTP

Answer Source

You may use ngChange to check if your input is null whenever you make a change to your input. In your html, something like:

<input type="text" ng-model="input.text" ng-change="validate()" />

And in your AngularJS controller:

function validate() {
   if ($scope.input.text === null) {
     delete $scope.input[text]; // First option
     delete $scope.input.text;  // Second option

You can apply this to any field, too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download