AngularJs alternative to ng-if to save digest

2019-05-25 05:13发布

问题:

I recently started studying about digest and performance improvements in AngulaJs and found on my website that I'm using tons of ng-if.

Sometimes in ng-if there is a variable that may change, but often is fixed at the startup of the controller and then never changes.

What should I do so to improve performance avoiding digest to evaluate every loop those unchangeable ng-if? Should I change directive? With what?

E.g

In my header template I have a div that can be seen only by particular type of user. It's just a div, so I don't want to call some different template. I put <div ng-if="userIsSuperior()"> ... </div>

When first evaluated, the return vale of userIsSuperior() never changes (during this session of course), but I know that AngularJs Digest evaluates it every loop. How can I avoid this? Or am I missing something?

回答1:

I think what you are looking for is one-time binding.

If you use:

<div ng-if="::userIsSuperior()"> ... </div>

Then the value of userIsSuperior() will only be calculated once and will stick to that value.

See demo.



回答2:

First answer solutions needs AngularJS > 2.

I found a valid solutions in using OnceJS, library for one-time-binding.

Here