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
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/
I try and avoid using watchers for performance reasons. With that being said, this really isn't as much of an Angular question as it is a JavaScript question. Since you have total control over when the data is passed off to the service I would simply clean it up first. This is fairly simple since your data structure is so shallow.
https://jsfiddle.net/1ua6oj5e/9/
(function() {
var formApp = angular.module("formApp", []);
formApp.controller("FormCtrl", function ($scope, $timeout) {
// Remove junkiness
var _remove = function remove(item) {
if ($scope.formData.title === undefined || $scope.formData.title === '') {
delete $scope.formData.title;
}
};
$scope.formData = {};
$scope.formData.subscribers = [
{ name: null, email: null }
];
$scope.addSubscriber = function() {
$scope.formData.subscribers.push({ name: null, email: null });
};
// Submit to test functionality
$scope.submit = function() {
// Remove title if empty
_remove($scope.formData.title);
/* Remove name and email if empty.
* If your list of fields starts to get large you could always
* just nest another iterator to clean things up.
*/
angular.forEach($scope.formData.subscribers, function(sub) {
_remove(sub.name);
_remove(sub.email);
});
};
});
})();
Added Watcher on formData,
$scope.$watch('formData',function(n,o){
if(typeof $scope.formData.title !== 'undefined' && $scope.formData.title === "" ){
delete $scope.formData.title;
}
},true);
Updated fiddle: https://jsfiddle.net/1ua6oj5e/6/
For all the dynamic fields you should use angular form validation, you should see this: https://docs.angularjs.org/guide/forms
function replacer(key, value) {
if (value == "" || value == null) {
return undefined;
}
return value;
}
var foo = {foundation: "", model: {year: 2015, price:null}, week: 45, transport: "car", month: 7};
foo = JSON.stringify(foo, replacer);
foo =JSON.parse(foo);
console.log(foo);