1
\$\begingroup\$

I have 4 ng-if which are related with the same conditions properties:

<a ng-if="action.state && !action.params && !action.href && !action.callback"
   ui-sref="{{ action.state }}">
     {{ action.label }}
</a>
<a ng-if="action.state && action.params && !action.href && !action.callback"
   ng-click="$ctrl.stateGo(action.state, action.params)">
     {{ action.label }}
</a>
<a ng-if="action.href && !action.params && !action.state && !action.callback"
   ng-href="{{ action.href }}">
     {{ action.label }}
</a>
<a ng-if="action.callback && !action.params && !action.state && !action.href"
   ng-click="action.callback()">
     {{ action.label }}
</a>

How can I improve the code with a method that manages all that with parameters, using a map for example?

Solution :

Template :

<a class="text-center"
   ng-if="::$ctrl.navigationType('state', action)"
   ui-sref="{{ action.state }}">
  {{ action.label }}
</a>
<a class="text-center"
   ng-if="::$ctrl.navigationType('params', action)"
   ng-click="$ctrl.stateGo(action.state, action.params)">
  {{ action.label }}
</a>
<a class="text-center"
   ng-if="::$ctrl.navigationType('href', action)"
   ng-href="{{ action.href }}">
  {{ action.label }}
</a>
<a class="text-center"
   ng-if="::$ctrl.navigationType('callback', action)"
   ng-click="action.callback()">
  {{ action.label }}
</a>

Controller :

  navigationType(navigationType, action) {
    const map = {
      'state': action.state && !action.params && !action.href && !action.callback,
      'params': action.state && action.params && !action.href && !action.callback,
      'href': action.href && !action.params && !action.state && !action.callback,
      'callback': action.callback && !action.params && !action.state && !action.href
    }
    return map[navigationType]
  }

Someone has an improvement?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.