Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 330
Le Thanh Avatar asked Feb 24 '16 04:02

Le Thanh


1 Answers

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;
}
like image 111
Shashank Agrawal Avatar answered Nov 04 '22 19:11

Shashank Agrawal