ng-model: empty strings should be null

前端 未结 1 1630
深忆病人
深忆病人 2020-12-24 14:01

If I use ng-model for an input field and empty it, angular sets it to \'\' instead of null even if it was null before.

相关标签:
1条回答
  • 2020-12-24 14:48

    You may want to $watch for the empty value and set it to null:

    <input type="text" ng-model="test.value" />
    
    $scope.$watch('test.value', function (newValue, oldValue) {
      if(newValue === "")
        $scope.test.value = null;
    });
    

    Another way would be to use a custom directive and apply a $parsers in it:

    <input type="text" ng-model="test.value" empty-to-null />
    
    myApp.directive('emptyToNull', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attrs, ctrl) {
                ctrl.$parsers.push(function(viewValue) {
                    if(viewValue === "") {
                        return null;
                    }
                    return viewValue;
                });
            }
        };
    });
    
    0 讨论(0)
提交回复
热议问题