有条件地在angular.js中添加一个元素属性[复制]

时间:2022-01-18 11:42:47

This question already has an answer here:

这个问题在这里已有答案:

I'm trying to add an autoplay attribute to a video tag based on the is_autoplay scope variable.

我正在尝试根据is_autoplay范围变量向视频标记添加自动播放属性。

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">
    ...

2 个解决方案

#1


6  

One Simple solution would be to use ng-if to generate the dom based on the condition.

一个简单的解决方案是使用ng-if根据条件生成dom。

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.

因此,如果is_autoplay为true,则第一个元素将使用autoplay属性生成,第二个元素将不在dom中。

If is_autoplay is false, the second dom element will be generated without the autoplay attribue.

如果is_autoplay为false,则将生成第二个dom元素而不使用autoplay属性。

#2


2  

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

您还可以根据is_autoplay属性直接设置autoplay属性:

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

#1


6  

One Simple solution would be to use ng-if to generate the dom based on the condition.

一个简单的解决方案是使用ng-if根据条件生成dom。

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.

因此,如果is_autoplay为true,则第一个元素将使用autoplay属性生成,第二个元素将不在dom中。

If is_autoplay is false, the second dom element will be generated without the autoplay attribue.

如果is_autoplay为false,则将生成第二个dom元素而不使用autoplay属性。

#2


2  

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

您还可以根据is_autoplay属性直接设置autoplay属性:

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