AngularJS形式和null /空值

Web*_*ser 8 html javascript angularjs angularjs-scope

我正在使用一个有点动态的AngularJS表单.换句话说,我能够添加输入字段等行.所以我的方法是从一个$scope.formData空对象开始,封装绑定到静态和动态HTML表单元素的所有属性.

AngularJS代码如下:

(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 });
        };
    });
})();
Run Code Online (Sandbox Code Playgroud)

AngularJS表单的HTML:

<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>
Run Code Online (Sandbox Code Playgroud)

请注意最后的Debug info部分,它显示$scope.formData对象及其内容.我对实现此表单的方式有几个问题.

  • 页面首次加载时,没有formData.title属性$scope,但由于它绑定到标题输入文本字段,当我开始键入值时,title属性将被添加到$scope.但是,当我删除输入文本字段中的值时,该formData.title属性仍然$scope作为空字符串存在.我想这没关系,但我真的想在提交表单时清理空值或空值.如果容易这样做,我想在客户端这样做,所以服务器端代码不必清理任何东西.
  • 使用动态订阅者部分,我可以继续添加任意数量的行,但最终,我想过滤掉客户端上的所有空订阅者对象.

AngularJS是否有任何选项可以$scope在进一步处理之前检测和清除空/空值,例如$httpPOST?

注意我为这个例子设置了一个jsFiddle.

Ata*_*ury 1

在formData上添加了Watcher,

$scope.$watch('formData',function(n,o){
      if(typeof $scope.formData.title !== 'undefined' && $scope.formData.title === "" ){
        delete $scope.formData.title;
      }
},true);
Run Code Online (Sandbox Code Playgroud)

更新的小提琴:https ://jsfiddle.net/1ua6oj5e/6/

对于所有应使用角度表单验证的动态字段,您应该看到以下内容: https: //docs.angularjs.org/guide/forms