Angular.js: Conditionally add an element attribute

Created on 10 Jun 2014  路  9Comments  路  Source: angular/angular.js

How can I add autoplay attribute to video tag based on the scope variable is_autoplay?

Most helpful comment

The following doesn't seems to work though

ng-attr-ui-sref="{{sref && sref + '(' + getParams(item) + ')' || undefined}}"
# Cannot read property 'match' of undefined

or

ng-attr-ui-sref="{{sref && sref + '(' + getParams(item) + ')' || 'undefined'}}"
# Could not resolve 'undefined' from state XXXX

ui-sref is always added even if the result of ng-attr-ui-sref is `undefined

All 9 comments

ng-attr-autoplay="is_autoplay"?

thanks, but not working.

I confirmed that is_autoplay holds true, but autoplay attribute is not added.

Hmm. You could make it via:

angular.module('autoplayAttribute', []).directive('autoplay',
    function () {
        return {
            link: function (scope, el, attrs) {
                scope.$watch(
                    function () { return attrs.autoplay; },
                    function (newVal) { attrs.$set('autoplay', newVal); }
                );
            }
        };
    });

Off the top of my head, and I'm sure there's something more optimal/minimal, but something like that should work...

Thanks!

but in any case ng-attr-something doesnt works :(

This works as expected since version 1.3.0-rc.0 (demo).

Note that ng-attr-something uses interpolation, so you need to wrap the expression in {{...}}.
In order for the attribute to be removed, (any sub-part of) the expression has to evaluate to undefined.

thanks

This works for me ng-attr-myattribute="{{myBooleanCondition ? '' : undefined}}"

The following doesn't seems to work though

ng-attr-ui-sref="{{sref && sref + '(' + getParams(item) + ')' || undefined}}"
# Cannot read property 'match' of undefined

or

ng-attr-ui-sref="{{sref && sref + '(' + getParams(item) + ')' || 'undefined'}}"
# Could not resolve 'undefined' from state XXXX

ui-sref is always added even if the result of ng-attr-ui-sref is `undefined

Was this page helpful?
0 / 5 - 0 ratings