0

I have an attribute on an HTML element that I want to give a value based on a series of conditions.

For example, if article.fields.category==='Example One' I want to give my element the attribute am-icon with the value example-one. If however article.fields.category==='Another Example' it needs the value another-example and so on for a whole list.

I've tried this:

<i ng-attr-am-icon="{'example-one': article.fields.category==='Example One' || 'another-example': article.fields.category==='Another Example' || || 'third-example': article.fields.category==='Third Example'}"></i>

This does not apply the attribute and I'm pretty sure I'm writing it wrong. But I can't seem to find documentation on ngAttr or examples of how to do this.

The desired result would be one of the following, based on the condition met:

<i am-icon="example-one"></i>
<i am-icon="another-example"></i>
<i am-icon="third-example"></i>

2 Answers 2

2
<i ng-attr-am-icon="{'example-one': article.fields.category==='Example One', 
                     'another-example': article.fields.category==='Another Example', 
                     'third-example': article.fields.category==='Third Example'}">
</i>

Actually above might not work so well but @Deepika Kamboj deserves an upvote. To correct my error, maybe...

<i ng-attr-am-icon="{{ getAttr(article.fields.category) }}"></i>

and

$scope.getAttr = function(val)  {
  return ($filter('lowercase')(val)).replace(' ', '-');
};
Sign up to request clarification or add additional context in comments.

Comments

1

The way I would do it is to create a method in the controller that evaluates the condition and gives back the result. The advantage of this approach is that you can test the logic in your controller which is not possible in html.

<i am-icon="getResult(article.fields.category)"></i>

In controller:

$scope.getResult = function(category) {
   if(category === 'Example One'){
      return 'Example One';
   }
   else if(category === 'another-example'){
      return 'another-example';
   }
};

1 Comment

Yeh that works but as I say I've got a whole list of possibilities. I don't really want 20 lines of if statements cluttering my controller if I can do it in the HTML

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.