How to store cents in Angular math function

I have a math function that adds two input fields and puts a value in the third. I also have a filter that adds cents to the input. you will see in plunkr that the filter does not apply to the revised contract. Original Contract + Total CO = Revised Contract. plunkr

$scope.$watch('currentItem.JobOriginalContract -- currentItem.JobTotalCO', function (value) {
    if (!$scope.currentItem) $scope.currentItem = {};
    $scope.currentItem.JobRevisedContract = value;
});
$scope.$watch('currentItem.JobRevisedContract * .85 ', function (value) {
    if (!$scope.currentItem) $scope.currentItem = {};
    $scope.currentItem.JobOriginalBudget = value;
});

      

+3


source to share


1 answer


$parsers

is only triggered when the ngmodel value is changed from the DOM (for example: - typing in an input field). When you programmatically change the value (as with JobRevisedContract

and JobOriginalBudget

), it is executed $formatters

. Therefore, you will need to format in formatters.

Example: -



    ctrl.$formatters.unshift(function (a) {
      return getFormattedValue(ctrl.$modelValue);
    });

    ctrl.$parsers.unshift(function (viewValue) {
        var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
        elem.val(getFormattedValue(plainNumber));
        return plainNumber;
    });

    function getFormattedValue(value){
      return $filter(attrs.format)(value/100,2);
    }

      

Demo

+3


source







All Articles