Attribute without value in AngularJS directive

放肆的年华 提交于 2019-12-22 05:24:27

问题


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.


回答1:


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

    }



回答2:


I know it is an old question, but there is that way to:

link: function(scope, elem, attrs) {
  scope.noValueAttr = scope.$eval(attrs.noValueAttr) || 'default value';
}


来源:https://stackoverflow.com/questions/27285925/attribute-without-value-in-angularjs-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!