Javascript AngularJS 表单和空/空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29725499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:51:48  来源:igfitidea点击:

AngularJS form and null/empty values

javascripthtmlangularjsangularjs-scope

提问by Web User

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.formDataempty object, to encapsulate all the properties that are bound to both static and dynamic HTML form elements.

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

The AngularJS code is as follows:

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

The HTML for the AngularJS form:

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>

Note the Debug infosection at the end, which displays the $scope.formDataobject and its contents. I have a couple of issues with the way I have implemented this form.

请注意最后的调试信息部分,其中显示了$scope.formData对象及其内容。我在实施此表单的方式上有几个问题。

  • When the page first loads, there is no formData.titleproperty in the $scope, but since it is bound to the Title input text field, when I start typing a value, the titleproperty gets added to the $scope. However when I delete the value in the input text field, the formData.titleproperty still exists in the $scopeas 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 Subscriberssection, I can keep adding as many rows as I want, but ultimately, I would like to filter out all empty subscriberobjects on the client side.
  • 页面首次加载时, 中没有formData.title属性$scope,但由于它绑定到 Title 输入文本字段,因此当我开始输入值时,该title属性会添加到$scope. 但是,当我删除输入文本字段中的值时,该formData.title属性仍然$scope以空字符串的形式存在。我想这没问题,但我真的想在提交表单时清理空值或空值。如果这样做很容易,我想在客户端执行此操作,因此服务器端代码不必清理任何内容。
  • 使用动态订阅者部分,我可以根据需要继续添加任意数量的行,但最终,我想过滤掉客户端的所有空订阅者对象。

Does AngularJS have any options for detecting and cleaning null/empty values in the $scopebefore further processing, such as a $httpPOST?

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

NoteI have set up a jsFiddlefor this example.

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

回答by Tome Pejoski

Simply use ngModelController$parsers and overwrite the default HTML input element.

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

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.

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

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/

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

回答by Scott Sword

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.

出于性能原因,我尽量避免使用观察者。话虽如此,这确实不是一个 Angular 问题,而是一个 JavaScript 问题。由于您可以完全控制数据何时传递给服务,因此我会先将其清理干净。这相当简单,因为您的数据结构非常浅。

https://jsfiddle.net/1ua6oj5e/9/

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

        };
    });
})();

回答by Raj

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

回答by Ataur Rahim Chowdhury

Added Watcher on formData,

在 formData 上添加了 Watcher,

$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/

更新小提琴: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

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