Check existence of attribute in AngularJs Directive

前端 未结 4 391
难免孤独
难免孤独 2021-02-05 00:33

Is is possible to check whether a given attribute is present in a directive, ideally using isolate scope or in a worst case scenario the attributes object.

With a direct

相关标签:
4条回答
  • 2021-02-05 01:20

    Since the attrs value is type of javascript object. To check attribute existence we can also using hasOwnProperty() method instead in keyword.

    So, it could be :

    link: function(scope, element, attrs) {
      var is_key_exist = attrs.hasOwnProperty('status');//Will return true if exist
    }
    

    You can read further the difference between in keyword and hasOwnProperty() method at this link

    0 讨论(0)
  • 2021-02-05 01:22

    To Check for attributes when using angular 1.5+ components you can use the $postLink lifecycle hook and the $element service like this:

    constructor(private $element) {}
    
    $postLink() {
      if(!this.$element.attr('attr-name')){
        // do something
      }
    }
    
    0 讨论(0)
  • 2021-02-05 01:27

    The way to do what you want is by looking at the attribute object in the link function:

    link: 
      function(scope, element, attrs) {
        if("status" in attrs)
           //do something
      }
    
    0 讨论(0)
  • 2021-02-05 01:34

    The way to do this is to check for the existence of the attributes within the link function's attrs parameter, and assign this to variables within your directive's isolate scope.

    scope:{},
    link: function(scope, element, attrs){
      scope.status = 'status' in attrs;
    },
    

    This should work without having to use an if statement within your link function.

    0 讨论(0)
提交回复
热议问题