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?
4 Answers 4
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)
})
1 Comment
get element by id and set new attribute and value
var el =angular.element('#divId');
el.attr('attr-name', 'attr-value');
2 Comments
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');
1 Comment
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
1 Comment
Explore related questions
See similar questions with these tags.
function_name.