Angularjs dynamically set attribute

2019-01-11 17:49发布

问题:

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

 var table = document.getElementById("div_id").setAttribute("ng-click", "function_name()");
 $scope.$apply();

Everything looks fine, in the debugger i see that attribute was added but it doesn't execute my function. Do you have any ideas how to add attributes to the existing div and how to make it works?

回答1:

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/



回答2:

get element by id and set new attribute and value

 var el =angular.element('#divId');
 el.attr('attr-name', 'attr-value');


回答3:

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');


回答4:

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