【发布时间】:2017-03-20 12:37:49
【问题描述】:
上下文:我正在开发我的应用的移动版本。我希望用户能够使用他们的手机/平板电脑的numeric keybord 输入数字字段。 AngularJS 使带有type = "number" 的输入字段对于任何非整数数据(这是任意的,因为输入是一个字符串)都无法访问。
想法:我想做一个指令,以某种方式(使用$watch 或$parsers 或任何其他古老的巫术)将输入字符串转换为数字。
问题:当我在输入字段中键入任何内容时,我的指令不会触发 $watch 的更改。 但是当我从我的控制器更改范围字段时,$watch 会按计划触发。
控制器:
// code minimized and omitted for clarity
.controller('carController', ['$scope', function ($scope) {
$scope.car = {
power : null,
// other fields
}
}]);
指令
angular.module('numeric', []).directive('numeric', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel'
},
link: function (scope, element, attrs, ngModelCtrl) {
// parsers does not affect anything
ngModelCtrl.$parsers.push(function(value) {
return parseInt(value);
});
// watcher does not watch
scope.$watch('model', function(newVal, old) {
if (typeof newVal == 'string') {
scope.car.power = parseInt(newVal);
}
}, true);
}
};
});
html
<div ng-controller="carController">
<input
ng-model="car.power"
numeric
name="power"
type="number"
pattern="[0-9]">
</div>
这是一个演示这种行为的小提琴http://jsfiddle.net/xo94sw7m/1/
问题:我缺少什么以及如何使指令按计划工作?
我尝试过:使用 $formatters-$parsers,使用不同的 $watch 方法(使用scope:false,隔离范围,尝试使用attrs 等来观察范围变化),到目前为止似乎没有任何效果
【问题讨论】:
-
我没看出问题,
<input type="number">完全支持浮点数 -
如果您阅读问题或访问小提琴链接,您可能会看到问题。
-
我阅读了这个问题并访问了小提琴,但你为什么将浮点数存储为字符串?只需将其存储为浮点数。
-
我没有将浮点数存储为字符串:) 我的问题中唯一的浮点数是
parseFloat(),这只是糟糕的复制粘贴,我用parseInt()替换。但这并没有什么区别——type=number会阻塞....等等。看来你是对的,我刚刚删除了我的指令并且输入被接受jsfiddle.net/aqkobhux我不明白最初是什么错误...... -
@RonDadon 看来问题出在
pattern="[0-9]"属性中...谢谢您的帮助!
标签: javascript angularjs input angularjs-directive