Jasmine
Jasmine

Reputation: 5326

checking multiple condition in ng-if

I need to check 4 conditions in ng-if which are boolean conditions. If any of them is true, I need to display some div.

Is there any simple and better way to do it please?

<div ng-if="ctrl.survivor || ctrl.doctor || ctrl.patient || ctrl.beneficiary">
<div ng-bind-html=" {{ myContent }}">
</div>
</div>

Upvotes: 0

Views: 1329

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

In general, complex logic inside of angular expressions is a code smell:

  • hard to read
  • hard to debug
  • hard to test

In general, I try to avoid boolean logic or anything else that indicates complexity in angular expressions that I write or code review. Instead, I recommend that you extract the logic into a controller method and call the controller method directly. This allows you to also write a nice unit test for it. The final code that I would recommend would look something like this:

<div ng-if="ctrl.isApplicable()">
  <div ng-bind-html=" {{ myContent }}"></div>
</div>

In the controller:

class Ctrl {
  ...    
  isApplicable() {
    return survivor || ctrl.doctor || ctrl.patient || ctrl.beneficiary;
  }
  ...
}

Upvotes: 1

Related Questions