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">
    ...
adeltahir
  • 1,087
  • 2
  • 15
  • 31
  • 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': ``. It’s removed because ng-attr- has the allOrNothing feature of removing an attribute if the expression yields undefined. – Gianpiero Mar 02 '17 at 11:31

2 Answers2

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.

guru
  • 4,002
  • 1
  • 28
  • 33
0

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

<video autoplay="{{is_autoplay}}">...</video>
kaybab
  • 53
  • 7
  • 5
    "The autoplay attribute is a boolean attribute.When present, the audio will automatically start playing as soon as it can do so without stopping." – Watchmaker Jun 10 '16 at 09:51