23

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">
    ...
1
  • 1
    I know it is late, but can be useful. For angular 1.3+ and attribute without values (e.g. autoplay or required) you can use 'undefined': <video ng-attr-autoplay="is_autoplay || undefined">...</video>. It’s removed because ng-attr- has the allOrNothing feature of removing an attribute if the expression yields undefined. Commented Mar 2, 2017 at 11:31

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. I know this would work, but this method is not always a good choice.
0

You can also directly set the autoplay attribute based on your is_autoplay property:

<video autoplay="{{is_autoplay}}">...</video>

1 Comment

"The autoplay attribute is a boolean attribute.When present, the audio will automatically start playing as soon as it can do so without stopping."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.