I\'m trying to dynamically add attribute to div in controller in angular js.
var table = document.getElementById(\"div_id\").setAttribute(\"ng-click\", \"f
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
get element by id and set new attribute and value
var el =angular.element('#divId');
el.attr('attr-name', 'attr-value');
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');
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/