I'm currently trying to have the input value automatically remove the any leading 0's that might come up for a some numbers. For example, in the snipper below, I have an onchange function that automically converts all numbers into integers and forces any negative values to 0. However when attempting to get rid of the leading 0, the input box doesn't change while the value stored inside the ngModel (number.num) accurately gets rid of the leading 0.
angular.module('app1', []) //
.controller('FormCtrl', function($scope) {
$scope.number = {'num': 0};
$scope.numberOnChange = function() {
$scope.number.num = parseInt($scope.number.num.toString(), 10)
console.log($scope.number.num)
if (!$scope.number.num || $scope.number.num < 0) $scope.number.num = 0
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app=app1 ng-controller="FormCtrl">
<form>
<input type=number ng-model="number.num" ng-change="numberOnChange()">
</form>
</div>
CodePudding user response:
It seems that the browser is adding it, not sure how to control it...
So try using a directive instead: move the code to the directive, and render modified value.
Try this:
angular.module('app1', [])
.directive('noLeadingZeroes', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
elm.bind('propertychange keyup paste', function(blurEvent) {
scope.$apply(function() {
const val = ctrl.$viewValue;
console.log('directive val:', val);
let clean = parseInt(val.toString(), 10)
if (!clean || clean < 0) clean = 0
ctrl.$setViewValue(clean);
ctrl.$render();
});
});
}
}
})
.controller('FormCtrl', function($scope) {
$scope.number = {'num': 0 };
$scope.numberOnChange = function() {
console.log('controller val: ', $scope.number.num);
}
});
.as-console-wrapper { max-height: 20% !important; bottom: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app=app1 ng-controller="FormCtrl">
<form>
<input type=number no-leading-zeroes ng-model="number.num" ng-change="numberOnChange()">
</form>
</div>
CodePudding user response:
angular.module('app1', []) //
.controller('FormCtrl', function($scope) {
$scope.number = {'num': 0};
$scope.numberOnChange = function() {
$scope.number.num = parseInt($scope.number.num.toString(), 10)
console.log($scope.number.num)
if (!$scope.number.num || $scope.number.num < 0) $scope.number.num = 0
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app=app1 ng-controller="FormCtrl">
<form>
<input type=text ng-model="number.num" ng-change="numberOnChange()">
</form>
</div>