Skip to content Skip to sidebar Skip to footer

Angularjs Formatted Number Calculation

Yesterday, I am having trouble on how to make a formatted number in my number fields but now that I achieve it, I am having problem on how to do the calculation. index.html

Solution 1:

The only solution I can think of is to watch for changes in {{ var.value }} on the controller:

functionMyCtrl($scope) {
    $scope.var = {"value":1000.36};

    $scope.$watch('var.value', function(val) {
        $scope.numbericVal = accounting.unformat(val);
    });
}

And then, use numericVal in your view like this: {{numbericVal * 2}}

Example: http://jsfiddle.net/1syh7cne/7/


Another RAW example that using callback function whenever the value gets changed: http://jsfiddle.net/1syh7cne/9/

I've used the attributes to define a function that pass the object and the current numeric value. Note that you can just parse the val of the passed object instead of trusting the second parameter in the function.

var invoker = $parse(attrs.updateFunc);
invoker(scope, {number: plainNumber});

Just take a look - I think you'll see what I did there. But as I said - It's a general direction for a possible solution.

Solution 2:

If you are not limited to using only Angular you can check out accounting.js library which does exactly what you need.

Then you could also keep a variable on $scope, that you use for calculation only, and you maintain the state between your var.value and that other $scope variable with help of accounting.js for formatting.

I hope this helps. Good luck.

Post a Comment for "Angularjs Formatted Number Calculation"