Angularjs dynamically set attribute

后端 未结 4 1165
借酒劲吻你
借酒劲吻你 2020-12-05 10:08

I\'m trying to dynamically add attribute to div in controller in angular js.

 var table = document.getElementById(\"div_id\").setAttribute(\"ng-click\", \"f         


        
相关标签:
4条回答
  • 2020-12-05 10:35

    Angular2 is providing [attr.<attribute name>] to bind attribute values.

    <div id="divID" [attr.role]="roleVal">
      This text color can be changed
    </div>
    

    In component class:

      addAttr() {
        this.roleVal = 'admin';
      }
    
      removeAttr() {
        this.roleVal = '';
      }
    
      checkAttr() {
        alert(this.roleVal);
      }
    

    From http://blog.sodhanalibrary.com/2016/02/set-attribute-and-remove-attribute-with.html

    0 讨论(0)
  • 2020-12-05 10:37

    get element by id and set new attribute and value

     var el =angular.element('#divId');
     el.attr('attr-name', 'attr-value');
    
    0 讨论(0)
  • 2020-12-05 10:41

    To Set attribute dynamically use

    var myEl = angular.element(document.querySelector('#divID'));
    myEl.attr('myattr',"attr val");
    

    To get attribute value use

    var myEl = angular.element( document.querySelector('#divID'));
    alert(myEl.attr('myattr'));
    

    To remove attribute use

    var myEl = angular.element( document.querySelector( '#divID' ) );
    myEl.removeAttr('myattr');
    
    0 讨论(0)
  • 2020-12-05 10:46

    You need to recompile your div

    var el = angular.element("div_id");
    $scope = el.scope();
    $injector = el.injector();
    $injector.invoke(function($compile){
       $compile(el)($scope)
    })
    

    http://jsfiddle.net/r2vb1ahy/

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