I have an Angular.js app that performs a large set of accounting-type calculations (revenue, costs, profit, etc) across a complex object model. A change to any part of the object model requires all of the calculations to be re-executed. Furthermore, many of the changes to the object model can be made directly from my templates using bindings - there's no need for a controller to intermediate.
Many of the calculation results need to both be displayed to the user and contribute to downstream calculations. For example, revenue is displayed to the user but is also used to calculate the profit (which is also displayed to the user). However, there's no point in calculating the revenue twice (it's a complex calculation) on each digest cycle, so an obvious optimization is to memoize when it is first calculated and then reuse this memoized value for the duration of the cycle.
The problem is that I need to clear these memoizations either at the beginning or end of the digest cycle. One approach would be for the controller to intercept every possible source of changes and manually unmemoize the object model before proceeding with the calculations. Instead, I'd much prefer to just keep using the bindings that have been set up.
As far as I can tell, what I need is a way to know when either the digest cycle is starting, or when it has finished. When I get this notification, I could reset the memoizations.
The Angular $watch documentation says:
If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Since watchExpression can execute multiple times per $digest cycle when a change is detected, be prepared for multiple calls to your listener.)
This is no use to me because clearing the memoizations on each iteration of the digest cycle would defeat the purpose of having them in the first place. I need only one notification per digest cycle.
How can I do this, or is there an alternate approach to solving the problem?