gpt4 book ai didi

javascript - 允许用户使用angularjs在输入框中只输入正数

转载 作者:搜寻专家 更新时间:2023-11-01 04:45:10 24 4
gpt4 key购买 nike

我想允许用户在文本框中只输入正数

我的代码如下:

script.js 文件内容:

angular.module("myfapp", []).controller("HelloController", function($scope) {
$scope.helloTo = {};
$scope.helloTo.title = "AngularJS";
});

angular.module('myApp', []).controller('MainCtrl', function($scope) {
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if (!ngModelCtrl) {
return;
}

ngModelCtrl.$parsers.push(function(val) {
var clean = val.replace(/[^0-9]+/g, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});

element.bind('keypress', function(event) {
if (event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
});

angular.html内容如下:

<html>
<head>
<script src="angular.min.js"></script>
<script src="script.js"></script>

<style>
.entry {
width: 300px;
margin: 10px auto;
text-align: center;
}
</style>

</head>
<body ng-app="myfapp">
<div ng-controller="HelloController" >
<h2 class="entry">Welcome {{ helloTo.title }} to the world of Tutorialspoint!</h2>
</div>

<section ng-app="myApp" ng-controller="MainCtrl">
<h4 class="entry">AngularJS Numeric Value Widget</h4>
<div class="well entry">
<label>Employee Age
<input type="text" ng-model="employee.age" placeholder="Enter an age" valid-number/>
</label>
</div>
</section>

</body>

</html>

为什么不起作用?任何人都可以运行它并检查一下吗?

最佳答案

将您的输入类型更改为number,然后您可以使用min 指令来指定允许的最小数字。

<input type="number" ng-model="employee.age" placeholder="Enter an age" min="0"/>

关于javascript - 允许用户使用angularjs在输入框中只输入正数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34630263/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com