当输入类型编号为字符串AngularJS

时间:2018-03-08 15:38:55

标签: javascript angularjs

如果ng-model的值为"24" (string)而不是24 (number),则input[type="number"]会引发以下错误:

  

错误:[ngModel:numfmt] http://errors.angularjs.org/1.5.8/ngModel/numfmt?p0=24

我尝试将输入设置如下:

<input class="form-control" type="number" name="HouseNumber"
       ng-model="Number(HouseNumber)" />

但是,这也会引发错误:

  

错误:[ngModel:nonassign] http://errors.angularjs.org/1.5.8/ngModel/nonassign

如何让AngularJS忽略此错误/严格绑定,或将其自动转换为number中的ng-model

我无法将输入设置为type="text"

只是为了可视化错误

&#13;
&#13;
angular.module("app", [])

.controller("controller", function ($scope) {
  // I cannot simply change this in the actual code to $scope.number = 24;
  $scope.number = "24";
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <input type="number" ng-model="number"/>
</div>
&#13;
&#13;
&#13;

将输入类型更改为type="text"时,它可以正常工作
但是在实际代码中我无法做到这一点,因为输入应保留一个数字。

&#13;
&#13;
angular.module("app", [])

.controller("controller", function ($scope) {
  // I cannot simply change this in the actual code to $scope.number = 24;
  $scope.number = "24";
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <input type="text" ng-model="number"/>
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

如果您无法更改变量的初始化并转换字符串,请更改输入。 (如果山不会来到穆罕默德,那么穆罕默德必须去山上

您需要编写一个覆盖输入功能的指令。我已经采用了这个小功能,你可以随意改变你的应用程序:

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.x = "24";
});

app.directive('input', function() {
  return {
    restrict: 'E',
    require: 'ngModel',
    link: function(scope, $el, attrs, ngModel) {
      if ($el[0].type === "number") {
        ngModel.$parsers.push(function(value) {
          return Number(value);
        });
        ngModel.$formatters.push(function(value) {
          return parseFloat(value, 10);
        });
      }

    }
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <input type="number" ng-model="x">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

没有太多关于Angular的经验,但是简单的parseInt是否足以满足您的要求?

&#13;
&#13;
angular.module("app", [])

.controller("controller", function ($scope) {
  // I cannot simply change this in the actual code to $scope.number = 24;
  $scope.number = parseInt("24", 10);
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>

<div ng-app="app" ng-controller="controller">
  <input type="number" ng-model="number"/>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

input [type = number]需要一个数值,字段的角度装饰器会输入检查它。您必须将值强制转换为数字才能使用输入[type = number]字段。