What is the best way to conditionally apply attributes in AngularJS?

ID : 10183

viewed : 25

Tags : angularjsangularjs-directiveangularjs

Top 5 Answer for What is the best way to conditionally apply attributes in AngularJS?

vote vote

91

I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):

ng-attr-class="{{someBoolean && 'class-when-true' || 'class-when-false' }}" 

The same approach should work for other attribute types.

(I think you need to be on latest unstable Angular to use ng-attr-, I'm currently on 1.1.4)

vote vote

81

You can prefix attributes with ng-attr to eval an Angular expression. When the result of the expressions undefined this removes the value from the attribute.

<a ng-attr-href="{{value || undefined}}">Hello World</a> 

Will produce (when value is false)

<a ng-attr-href="{{value || undefined}}" href>Hello World</a> 

So don't use false because that will produce the word "false" as the value.

<a ng-attr-href="{{value || false}}" href="false">Hello World</a> 

When using this trick in a directive. The attributes for the directive will be false if they are missing a value.

For example, the above would be false.

function post($scope, $el, $attr) {       var url = $attr['href'] || false;       alert(url === false); } 
vote vote

70

I got this working by hard setting the attribute. And controlling the attribute applicability using the boolean value for the attribute.

Here is the code snippet:

<div contenteditable="{{ condition ? 'true' : 'false'}}"></div> 

I hope this helps.

vote vote

70

In the latest version of Angular (1.1.5), they have included a conditional directive called ngIf. It is different from ngShow and ngHide in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:

<h1 ng-if="editMode" contenteditable=true>{{content.title}}</h1> 
vote vote

59

To get an attribute to show a specific value based on a boolean check, or be omitted entirely if the boolean check failed, I used the following:

ng-attr-example="{{params.type == 'test' ? 'itWasTest' : undefined }}"

Example usage:

<div ng-attr-class="{{params.type == 'test' ? 'itWasTest' : undefined }}">

Would output <div class="itWasTest"> or <div> based on the value of params.type

Top 3 video Explaining What is the best way to conditionally apply attributes in AngularJS?

Related QUESTION?