HansMusterWhatElse
HansMusterWhatElse

Reputation: 671

AngularJS - $interpolate - Best way to add additional calculation logic

I've got the following code snippet (see below)

Whats the recommended way to add additional logic to the $interpolate string?

e.g I want to add tax to the amount.

{{amount + (amount / 100 * tax) | currency}}

instead of:

{{amount | currency}}

The problem is that this just appends the value to to the string.

How can I tell Angular that i want to work with numbers?

 .directive("evalExpression2", function ($parse, $interpolate) {
                var expressionFn = $parse("total | currency");
                var interpolationFn = $interpolate("The total is: {{amount | currency}}");
                return {
                    scope: {
                        amount: "=amount",
                        tax: "=tax",
                    },
                    link: function (scope, element, attrs) {
                        scope.$watch("amount", function (newValue) {
                            var localData = {
                                total: Number(newValue)
                                + (Number(newValue) * (Number(scope.tax) / 100))
                            }
                            //element.text(expressionFn(scope, localData));
                            element.text(interpolationFn(scope));
                        });
                    }
                }
            });

Upvotes: 0

Views: 1565

Answers (1)

Paul Sweatte
Paul Sweatte

Reputation: 24617

Use parentheses around the whole calculation:

{{ (amount + (amount / 100 * tax)  ) | currency }}

to avoid the | operator having precedence over the + operator.

References

Upvotes: 1

Related Questions