AngularJS 表单和空/空值 [英] AngularJS form and null/empty values

查看:25
本文介绍了AngularJS 表单和空/空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

AngularJS 代码如下:

(function() {var formApp = angular.module("formApp", []);formApp.controller("FormCtrl", function ($scope, $timeout) {$scope.formData = {};$scope.formData.subscribers = [{名称:空,电子邮件:空}];$scope.addSubscriber = function() {$scope.formData.subscribers.push({ name: null, email: null });};});})();

AngularJS 表单的 HTML:

<div data-ng-controller="FormCtrl"><p>主题名称:<input type="text" data-ng-model="formData.title" placeholder="输入标题"/></p>订阅者:<button data-ng-click="addSubscriber()">添加订阅者</button><表格><tr><th>姓名</th><th>电子邮件</th></tr><tr data-ng-repeat="formData.subscribers 中的订阅者"><td><input type="text" data-ng-model="subscriber.name" placeholder="输入姓名"/></td><td><input type="text" data-ng-model="subscriber.email" placeholder="输入电子邮件"/></td></tr><hr style="margin:1em 0;"/><p><em>调试信息</em>:{{ formData }}</p>

注意最后的 Debug info 部分,它显示了 $scope.formData 对象及其内容.我在实施此表单的方式上遇到了一些问题.

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

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

注意我已经为此示例设置了一个 jsFiddle.

解决方案

只需使用 ngModelController $parsers 并覆盖默认的 HTML 输入元素.

通过此实现,您可以始终控制模型值.因此,在您的情况下,只要视图值为空字符串,您就可以将模型设置为 null.

var inputDefinition = function () {返回 {限制:'E',要求:'?ngModel',链接:函数(范围、元素、属性、ngModel){如果(ngModel){var convertToModel = 函数(值){返回值 === '' ?空:值;};ngModel.$parsers.push(convertToModel);}}};/*** 覆盖默认输入元素.*/formApp.directive('input', inputDefinition);

这是更新的 JSFiddle:https://jsfiddle.net/9sjra07q/

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.

解决方案

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/

这篇关于AngularJS 表单和空/空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆