Here is my code in HTML (Angular):
<input ng-value="minLoanRange" tabindex="1" lable-up id="minLoanRange" class="inputMaterial" ng-model="minLoanRange" ng-disabled="activeType" type="number" max-length-handler required value="" ng-keyup="addCommas(minLoanRange)"/>
Here is my code of addCommas
:
$scope.addCommas = function(nStr){
nStr+='';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while(rgx.test(x1)){
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
$scope.minLoanRange = x1+x2;
}
I have put an alert just before $scope.minLoanRange = x1+x2;
like alert(x1+x2);
It is working properly, just not reflecting on screen.
You need to use two different variables - one for the model value and one for the value. Here's a working snippet to demonstrate how you can accomplish what you're after.
angular.module('app', []) .controller('controller', function($scope) { $scope.modelValue = 0; $scope.commaValue = ''; $scope.addComma = function() { let nStr = '' + $scope.modelValue.replace(',', ''); var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\\d+)(\\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } $scope.commaValue = x1 + x2; } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script> <div ng-app="app" ng-controller="controller"> <input ng-value="commaValue" ng-model="modelValue" ng-keyup="addComma()"> </div>
You don't need value=""
and ng-value
. Because ng-model supports two way binding. if you assign correct value to that model object. its automatically reflect to html.
I have copied the snippet from @lex answer and made some changes
angular.module('app', []) .controller('controller', function($scope) { $scope.modelValue = 0; $scope.commaValue = ''; $scope.addComma = function() { let nStr = '' + $scope.modelValue.replace(',', ''); var x = nStr.split('.'); var x1 = x[0]; var x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\\d+)(\\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } $scope.modelValue = x1 + x2; } });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script> <div ng-app="app" ng-controller="controller"> <input ng-model="modelValue" ng-keyup="addComma()"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.