Le Thanh
Le Thanh

Reputation: 227

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?

Upvotes: 7

Views: 2468

Answers (2)

xxxxx
xxxxx

Reputation: 1984

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.

Upvotes: 0

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

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;
}

Upvotes: 9

Related Questions