AngularJS form and null/empty values

前端 未结 4 1017
一整个雨季
一整个雨季 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条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-15 11:46

    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/

提交回复
热议问题