问题描述
我最近开始研究AngulaJs的摘要和性能改进,并在我的网站上发现我正在使用大量的ng-if
.
I recently started studying about digest and performance improvements in AngulaJs and found on my website that I'm using tons of ng-if
.
有时在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.
我应该怎么做才能提高性能,避免摘要来评估每个不变的ng-if
的每个循环?我应该更改指令吗?用什么?
What should I do so to improve performance avoiding digest to evaluate every loop those unchangeable ng-if
? Should I change directive? With what?
例如
在标题模板中,我有一个div,只有特定类型的用户才能看到.它只是一个div,所以我不想调用其他模板.我放了<div ng-if="userIsSuperior()"> ... </div>
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>
第一次评估时,userIsSuperior()
的返回值从不改变(在本次课程中),但是我知道AngularJs Digest会在每个循环中对其进行评估.如何避免这种情况?还是我错过了什么?
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?
推荐答案
我认为您正在寻找的是一次性绑定.
I think what you are looking for is one-time binding.
如果您使用:
<div ng-if="::userIsSuperior()"> ... </div>
然后userIsSuperior()
的值将只计算一次,并保持该值不变.
Then the value of userIsSuperior()
will only be calculated once and will stick to that value.
请参见演示.
这篇关于AngularJs替代ng-if以保存摘要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!