1

I am connected to an api and depending on the state of the player I change the text that shows up

div.meta(ng-if='friend.personastate == 6') Looking to play
div.meta(ng-if='friend.personastate == 5') Looking to trade
div.meta(ng-if='friend.personastate == 4') Snooze
div.meta(ng-if='friend.personastate == 3') Away
div.meta(ng-if='friend.personastate == 2') Busy
div.meta(ng-if='friend.personastate == 1') Online
div.meta(ng-if='friend.personastate == 0') Offline

I use the same thing for a class on a parent div :

ng-class='{grey: friend.personastate == 0, green: friend.personastate == 1, orange:friend.personastate == 2, yellow: friend.personastate == 3, blue:friend.personastate == 4}'

Is it fine to keep it like that because it's interface logic? Or I should make it a partial instead? I don't think it's the controller job to decide what color stuff should be.

gevorg
  • 4,835
  • 4
  • 35
  • 52
  • 1
    Well for series of ng-if, ng-switch was made for that situation. To simplify the ng-class, you could use the 3rd example in the selected answer here: http://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply-a-class I've never done ng-class that way and don't have time to at the moment, but I think the expression would be `{grey: 0, green: 1, orange: 2, yellow: 3, blue: 4}[friend.personastate]` – Tahsis Claus May 15 '16 at 22:40
  • @TahsisClaus I think you meant `{0 :"grey", 1: "green", 2:"orange", 3:"yellow", 4:"blue"}[friend.personastate]` Right? – Maxime Roussin-Bélanger May 15 '16 at 22:51

1 Answers1

3

An easy way to get rid of all ngIfs is to aggregate all the info into an object, using ngInit. This object looks something like this:

var stateInfo = {
  0: {
    text: 'Offline',
    class: 'grey'
  },
  1: {
    text: 'Online',
    class: 'green'
  },
  2: {
    text: 'Busy',
    class: 'orange'
  },
  // ...
  // You get the idea
  // ...
}

In the template you would be using <div class="meta">{{ stateInfo[friend.personastate].text }}</div> to display the text and ng-class='stateInfo[friend.personastate].class' to set the desired class.

One advantage of this approach is the reduced number of watchers.

Cosmin Ababei
  • 7,003
  • 2
  • 20
  • 34