I'm trying to add an autoplay attribute to a video tag based on the is_autoplay scope variable.
I searched all over the internet, but I couldn't find the exact snippet I wanted.
I tried following but none of them work.
<video autoplay="{{is_autoplay ? 'true' : 'false'}}">
...
<video ng-attr-autoplay="{is_autoplay}">
...
Someone even suggested the following
<video {{is_autoplay ? "autoplay" : ""}}>
...
The following solved my problem.
app.directive('attronoff', function() {
return {
link: function($scope, $element, $attrs) {
$scope.$watch(
function () { return $element.attr('data-attr-on'); },
function (newVal) {
var attr = $element.attr('data-attr-name');
if(!eval(newVal)) {
$element.removeAttr(attr);
}
else {
$element.attr(attr, attr);
}
}
);
}
};
});
Anyone can use this directive to add/remove attribute conditionally.
Usage
<video width="100%" height="100%" controls attronoff data-attr-on="{{is_autoplay}}" data-attr-name="autoplay">
...
One Simple solution would be to use ng-if
to generate the dom based on the condition.
For instance in your case, use
<video autoplay="true" ng-if="is_autoplay">...</video>
<video ng-if="!is_autoplay">...</video>
So if is_autoplay
is true
, the first element will be generated with the autoplay
attribute and second on will not be in dom.
If is_autoplay
is false
, the second dom element will be generated without the autoplay
attribue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With