texas697
texas697

Reputation: 6417

How to keep cents in a Angular math function

I have a math function that adds two input fields and puts the value in a third. I also have a filter that adds the cents to the input. you will see in the plunkr that the filter is not being applied 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;
});

Upvotes: 3

Views: 72

Answers (1)

PSL
PSL

Reputation: 123739

$parsers run only when you change the ngmodel value from the DOM (ex:- entering in the input box). When you programatically change the value (as you do for JobRevisedContract and JobOriginalBudget) it is $formatters that run. So you would 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

Upvotes: 3

Related Questions