AngularJS form and null/empty values

前端 未结 4 933
一整个雨季
一整个雨季 2021-02-15 11:20

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 11:46

    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);
                });
    
            };
        });
    })();
    

提交回复
热议问题