AngularJS 指令中没有值的属性 [英] Attribute without value in AngularJS directive

查看:21
本文介绍了AngularJS 指令中没有值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个带有隔离作用域的指令.

app.directive('myDirective', function() {返回 {限制:'E',范围 {属性 1: '@',attr2: '@',noValueAttr://这里放什么?},链接:功能(范围,元素,属性){//如何在这里检查标记中是否存在 noValueAttr?}};});

html 可以是

我想知道如何使用(并让指令检测它是否存在)一个没有赋值的可选属性.谢谢.

解决方案

只需在链接函数中使用 attrs.hasOwnProperty('noValueAttr') 来测试属性是否存在.>

不要忘记标记中的属性是 no-value-attr,而不是像你展示的 noValueAttr.

 链接:函数(范围,元素,属性){如果 (attrs.hasOwnProperty('noValueAttr'))//属性存在别的//属性不存在}

I've written a directive with an isolate scope.

app.directive('myDirective', function() {
    return {
        restrict: 'E',
        scope {
            attr1: '@',
            attr2: '@',
            noValueAttr: // what to put here?
        },
        link: function(scope, elem, attrs) {
            // how to check here if noValueAttr is present in mark-up?
        }
    };
});

the html could be

<my-directive attr1='...' attr='...' ... no-value-attr>

or

<my-directive attr1='...' attr='...' >

I am wondering how to use (and have the directive detect if it's there or not) an optional attribute which has no assigned value. Thanks.

解决方案

Just use attrs.hasOwnProperty('noValueAttr') in the link function to test whether the attribute is present or not.

Don't forget the attribute in markup would be no-value-attr, not noValueAttr like you showed.

 link: function(scope, elem, attrs) {
           if (attrs.hasOwnProperty('noValueAttr'))
              // attribute is present
           else 
              // attribute is not present

    }

这篇关于AngularJS 指令中没有值的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆