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?
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.Will produce (when value is false)
So don't use
false
because that will produce the word "false" as the value.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.
In the latest version of Angular (1.1.5), they have included a conditional directive called
ngIf
. It is different fromngShow
andngHide
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:Just in case you need solution for Angular 2 then its simple, use property binding like below, e.g. you want to make input read only conditionally, then add in square braces the attrbute followed by = sign and expression.
I am using the following to conditionally set the class attr when ng-class can't be used (for example when styling SVG):
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)
For input field validation you can do:
This will apply the attribute
max
to100
only ifdiscountType
is defined as%