AngularJS:输入类型=数字" 解析 ngModel 字符串值到数字并返回



我对angularJs很陌生。我的问题是:

我的模型数据保存在一个数据库中,如果一个项目被重新打开,数据将被显示。使用save,数据再次存储在数据库中。我在显示数字时遇到了问题因为该值存储为字符串,必须解析为整数。

这里是html:

 <numeric-input numericbinding="item.showInt" ng-model="item.operandvalue" ></numeric-input>

根据项目值的格式(bool、int、string),将以不同的方式显示operandvalue。这是由numericbinding的值指示的。

我尝试使用以下指令将字符串解析为int型:

.directive('numericInput', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: {
            model: '=ngModel',
            numericbinding: '='
        },
        template: '<input id="integerType" type="number" ng-model="intValue" ng-hide="!numericbinding" >',
        link: function (scope) {
            //avoid that string and bool is parsed,  showInt is false
            if (scope.numericbinding === false || scope.numericbinding === undefined) {
                return;
            }
           scope.intValue = parseInt(scope.model, 10);
        }
    };
})

这样可以正确显示数字。但是如果我想再次存储绑定项的数据。我在后端得到一个空指针。我明白我需要将数字转换回字符串。我尝试了多种方法,例如

  • ng-change:但是它从来没有进入给定的函数。

然后我想使用ngModelController和格式化器和解析器,如AngularJS中所述-在模板在自定义指令

中呈现之前格式化ng-model
.directive('numericInput', function () {
    return {
        restrict: 'E',
        require: 'ngModel',
        scope: {
            model: '=ngModel',
            numericbinding: '='
        },
        template: '<input id="integerType" type="number" ng-model="item.operandvalue" ng-hide="!numericbinding" >',
        link: function (scope, ngModelController) {
            //avoid that string and bool is parsed,  showInt is false
            if (scope.numericbinding === false || scope.numericbinding === undefined) {
                //console.log('not a number - return');
                return;
            }
            ngModelController.$formatters.unshift(function(valueFromModel) {
                return parseInt(valueFromModel, 10);
           });
            ngModelController.$parsers.push(function(valueFromInput) {
                return valueFromInput.toString();
            });
        }
    };
})

但是valueFromModel是未定义的。号码根本不显示。而且scope.item.operandvalue是未定义的。在Chrome中,错误是:TypeError: Cannot read property 'operandvalue' of undefined.

我想我应该保留这个东西。将数据绑定的Operandvalue作为字符串显示,并以不同的名称显示int值。在我看来,这个项目。Operandvalue得到一个数字,数据绑定不再工作。

我怎样才能解决我的问题?非常感谢您的帮助!

您可以使用两个字段:backing_field和binding_field。当读取db时,写入backing_field。然后可以使用它来更新binding_field,例如通过$watch。你可以用两块手表来保持同步。如果其中一个发生变化,您可以转换其值并将其写入另一个。你现在可能会说他会创建一个循环,但AngularJS检测到没有任何变化,不会再次触发。使用它,您可以在binding_field由于用户交互而更改时更新backing_field,并在从数据库获得新数据时通过backing_field更新binding_field。

最新更新