Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to be able to add for example "contenteditable" to elements, based on a boolean variable on scope.

Example use:

<h1 attrs="{'contenteditable=\"true\"': editMode}">{{content.title}}</h1> 

Would result in contenteditable=true being added to the element if $scope.editMode was set to true. Is there some easy way to implement this ng-class like attribute behavior? I'm considering writing a directive and sharing if not.

Edit: I can see that there seems to be some similarities between my proposed attrs directive and ng-bind-attrs, but it was removed in 1.0.0.rc3, why so?

like image 507
Kenneth Lynne Avatar asked Mar 29 '13 02:03

Kenneth Lynne


People also ask

What is attr in angular?

Attribute binding in Angular helps you set values for attributes directly. With attribute binding, you can improve accessibility, style your application dynamically, and manage multiple CSS classes or styles simultaneously.

How do you use NG disability?

Definition and UsageThe ng-disabled directive sets the disabled attribute of a form field (input, select, or textarea). The form field will be disabled if the expression inside the ng-disabled attribute returns true. The ng-disabled directive is necessary to be able to shift the value between true and false .


2 Answers

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)

like image 99
Ashley Davis Avatar answered Oct 05 '22 16:10

Ashley Davis


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); } 
like image 36
Reactgular Avatar answered Oct 05 '22 18:10

Reactgular