Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditionally add an element attribute in angular.js [duplicate]

Tags:

angularjs

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">
    ...
like image 646
adeltahir Avatar asked Jun 10 '14 08:06

adeltahir


1 Answers

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.

like image 168
guru Avatar answered Nov 14 '22 16:11

guru