Attribute without value in AngularJS directive

I wrote a directive with a selection area.

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? } }; }); 

html could be

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

or

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

I am wondering how to use (and indicate the directive, if there is one or not) an optional attribute that does not have an assigned value. Thanks.

+6
source share
2 answers

Just use attrs.hasOwnProperty('noValueAttr') in the link function to check if this attribute is present.

Remember that the markup attribute will be no-value-attr , not noValueAttr , as you showed.

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

I know this is an old question, but there is a way:

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

Source: https://habr.com/ru/post/979087/


All Articles