Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I refactor multiple conditions on ng-if in angularjs?

I have this code and I'm wondering if there is a better style to write this, so that there is less logic in the view.

<span ng-if="status == 'state1' || status == 'state2'">Foobar</span>
<span ng-if="status == 'state3'">Baz</span>
like image 551
crispychicken Avatar asked Mar 19 '23 23:03

crispychicken


2 Answers

Yes, I think refactoring is wise. Your example is simple, but it is easy to imagine having many more conditions. I've done something like this, when many elements have complicated display conditions:

$scope.render = {
  foobar: function() {
    return $scope.status == 'state1' || $scope.status == 'state2'
  },
  baz: function() {
    return $scope.status == 'state3'
  }
}

Then the usage in the view is:

<span ng-if="render.foobar()">Foobar</span>
<span ng-if="render.baz()">Baz</span>

Demo: http://plnkr.co/lv4w9dLN8oN0bBF23VKp

This keeps the logic footprint in the view small, and allows you to easily reuse the logic on multiple elements.

like image 174
j.wittwer Avatar answered Apr 05 '23 22:04

j.wittwer


Not sure if this is any better, but here is an option using ngSwitch. It does remove some logic (assuming you only have those three states):

<div ng-switch on="status">
    <span ng-switch-when="state3">Baz</span>
    <span ng-switch-default>Foobar</span>
</div>
like image 45
Andrew Clark Avatar answered Apr 06 '23 00:04

Andrew Clark