1

I'm trying to change the text in a title tag based on a tag's direction value:

<li ng-repeat="t in tags">
    <div class="tag"
         ng-class="{'green-up': t.direction == 'positive',
                    'red-down': t.direction == 'negative',
                    ''        : t.direction == 'stagnant'}"
                    title="Percentage increase"
                    ng-if="">{{t.name}}</div>
</li>

The direction is either positive, negative or stagnant, which should correspond to title="Percentage increase" title="Percentage decrease" or just title="Percentage"

What Angular syntax would be best used in this case?

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529
  • 1
    I would think about making a hash table and using `title={{ t.hashes[t.direction] }}` but that's not exactly 'angular' – LouisK Jul 11 '15 at 00:13

1 Answers1

3

Why not set up the tag settings as an object

$scope.tagInfo = {
    positive:{ class:"green-up", title:"Percentage increase" },
    negative:{ class:"red-down", title:"Percentage decrease" }
}

and then call that in your ng-repeat

<div class="tag"
     ng-class="tagInfo[t.direction].class"
     title="{{tagInfo[t.direction].title}}">{{t.name}}</div>

http://jsfiddle.net/rLrh0Lr1/

If you absolutely positively must use a conditional clause rather than a mapping lookup, call a method like f.e title="{{getTitle(t.direction)}}

$scope.getTitle = function(direction) {
    if (direction==="positive") {
        return "Increase";
    } else if (direction==="negative") {
        return "Decrease";
    }
};

http://jsfiddle.net/p6aysky5/

I don't really see the point at all of doing that though. All it contributes is making your code messier.

Jan
  • 5,688
  • 3
  • 27
  • 44
  • Yeah that is a way to do it, just didn't want to put more stuff into the model... for performance (100s of tags). Figured some kind of conditional in the markup may require less? I'll wait a bit more, but will check this if nothing else comes up, then just set my title to just `percentage` – Leon Gaban Jul 11 '15 at 01:00
  • I see no reason not to use a mappable object. Have you tried it and noticed a performance hit? There are better ways to increase performance than skimping out on doing things the "correct" way. `ng-if` wouldn't work, what it does is add or remove the entire element from the DOM. If you want a conditional clause inside your title, you still need to call a method accessible somewhere in the scope. Updated answer. – Jan Jul 11 '15 at 14:28