AngularJS形式和null /空值 [英] AngularJS form and null/empty values

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

问题描述

我正在使用一种动态的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});
};
});
} )();

AngularJS表单的HTML:

 < body data-ng-app =formApp> 
< div data-ng-controller =FormCtrl>
< p>
主题名称:< input type =textdata-ng-model =formData.titleplaceholder =输入标题/>
< / p>
订阅者:
<按钮data-ng-click =addSubscriber()>添加订阅者< / button>
< table>
< tr>
< th>名称< / th>
< th>电子邮件< / th>
< / tr>
< tr data-ng-repeat =formData.subscribers中的订阅者>
< td>< input type =textdata-ng-model =subscriber.nameplaceholder =enter name/>< / td>
< td>< input type =textdata-ng-model =subscriber.emailplaceholder =enter email/>< / td>
< / tr>
< / table>

< p>
< em>调试信息< / em>:{{formData}}
< / p>
< / div>
< / body>

请注意结尾处的调试信息部分,其中显示了 $ scope.formData 对象及其内容。




  • 第一次加载页面时,没有<$ c $在 $ scope 中的c> formData.title 属性,但由于它绑定到标题输入文本字段,所以当我开始键入一个值时,将 title 属性添加到 $ scope 中。但是,当我删除输入文本字段中的值时, formData.title 属性仍然存在于 $ scope 中作为一个空的字符串。我想这是好的,但我真的想在提交表单时清空空值或空值。我希望在客户端做到这一点,如果它很容易这样做,所以服务器端代码不需要清理任何东西。

  • 使用动态订阅服务器 / em>部分中,我可以继续添加尽可能多的行,但最终,我希望过滤掉客户端上的所有空订户对象。



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



我已经设置了 jsFiddle for this example。

解决方案

只需使用 ngModelController $解析器并覆盖默认的HTML输入元素。



通过这个实现,您可以控制整个模型的值时间。
因此,在您的情况下,只要视图值为空字符串,就可以将模型设置为null。



pre $ var inputDefinition = function(){
return {
restrict:'E',
require:'?ngModel',
link:function(scope,element,attr,ngModel){
if(ngModel){
var convertToModel = function(value){
返回值===''? null:value;
};
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形式和null /空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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