Should I reorganize a few ng-if conditions in angularjs?

I have this code, and I am wondering if there is a better style for writing this, so there is less logic in the view.

<span ng-if="status == 'state1' || status == 'state2'">Foobar</span>
<span ng-if="status == 'state3'">Baz</span>
+4
source share
3 answers

Yes, I think refactoring is wise. Your example is simple, but it’s easy to imagine that you have many conditions. I did something like this when many elements have complex display conditions:

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

Then use in view:

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

Demo: http://plnkr.co/lv4w9dLN8oN0bBF23VKp

This saves a logical trace in a small representation and makes it easy to reuse logic for multiple elements.

+4
source

, , , ngSwitch. (, ):

<div ng-switch on="status">
    <span ng-switch-when="state3">Baz</span>
    <span ng-switch-default>Foobar</span>
</div>
+2

If you expect your content to grow in the future, you can include it in a template directive or even the so-called conditional directive: link

+1
source

Source: https://habr.com/ru/post/1535422/


All Articles