How to decrease watchers inside AngularJS for ng-show with same condition
Asked Answered
F

2

7

In my HTML code, some div will display with the same condition. I set this condition to ng-show for each div.

<div ng-show="sameCondition1">...data1...</div>
...something else...
<div ng-show="sameCondition1">...data2...</div>
...something else...
<div ng-show="sameCondition1">...data3...</div>

AngularJS will create 3 watchers for each ng-show. It can affect performance. Is there any way to decrease the number of watchers in this case?

Fontainebleau answered 24/2, 2016 at 4:45 Comment(4)
Most of the times ng-if is better then ng-show/ng-hide.Jobless
This seems a little like micro-optimisation. ng-show creates a shallow watch, so it shouldn't be very expensive. If you want to optimise performance, eliminate deep watches and use ng-if to get rid of parts of the view that aren't needed at the moment where possible.Heteronym
@LeThanh, I've updated my answer. Please take a look.Polis
@ShashankAgrawal: I like your method!Fontainebleau
P
9

I'm not sure if this is possible but if you are using AngularJS > 1.3.x and your someCondition1 does not changes after one iteration then you can use Angular's feature of unregistering the watcher by using :: like below:

<div ng-show="::sameCondition1">...data1...</div>
...something else...
<div ng-show="::sameCondition1">...data2...</div>
...something else...
<div ng-show="::sameCondition1">...data3...</div>

Read more on One-time binding

Update

Since your condition will update, so my above solution won't work for you. But I've a cleaner solution to reduce the watcher to just 1 using CSS. Here you go:

<div class="{{sameCondition1 ? '' : 'hide-similar'}}">
    <div class="similar1">...data1...</div>
    ...something else...
    <div class="similar1">...data2...</div>
    ...something else...
    <div class="similar1">...data3...</div>
</div>

Now, define your CSS:

.hide-similar .similar1 {
    display: none;
}
Polis answered 24/2, 2016 at 4:56 Comment(2)
My condition will update based on user interaction, so one-way binding can not be applied in my case.Fontainebleau
Oh! Then my answer won't help in your case!!Polis
M
0

You can use ng-switch but it depends on the condition - if your conditions depend on a single variable (Example: a==1, a==2, a==3). It will reduce the watchers from 3 to 1.

Maffa answered 24/2, 2016 at 5:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.