I need to restrict the user to input only positive numbers in the text field
Here is my code snippet:
Contents of script.js file:
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();
}
});
}
};
});
});
Contents of 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>
Why is it not functioning properly? Could someone please test and verify it!