有条件加入angular.js元素的属性 [英] conditionally add an element attribute in angular.js
本文介绍了有条件加入angular.js元素的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想基础上,is_autoplay范围的变量自动播放属性添加到视频标签。
我找遍了互联网,但我无法找到确切的片段,我想。
我试着以下但他们没有工作。
<视频自动播放={{is_autoplay'真':'假'}}?>
...
<视频NG-ATTR自动播放={} is_autoplay>
...
有人甚至提出以下
<视频{{is_autoplay? 自动播放:}}>
...
下面的解决我的问题。
app.directive('attronoff',函数(){
返回{
链接:功能($范围,$元,$ ATTRS){
$范围。$手表(
函数(){$返回element.attr('数据ATTR上'); },
功能(的newval){
VAR ATTR = $ element.attr('数据ATTR名'); 如果(!的eval(的newval)){
$ element.removeAttr(attr)使用;
}
其他{
$ element.attr(ATTR,attr)使用;
}
}
);
}
};
});
任何人都可以使用这个指令添加/删除有条件属性。
用法
<视频WIDTH =100%HEIGHT =100%的控制attronoff数据ATTR式={{is_autoplay}}数据属性名称=自动播放>
...
解决方案
您也可以直接设置自动播放属性,根据您的is_autoplay属性:
<视频自动播放={{is_autoplay}}> ...< /视频>
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">
...
解决方案
You can also directly set the autoplay attribute based on your is_autoplay property:
<video autoplay="{{is_autoplay}}">...</video>
这篇关于有条件加入angular.js元素的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文