Angularjs dynamically set attribute
96,803
Solution 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)
})
Solution 2
get element by id and set new attribute and value
var el =angular.element('#divId');
el.attr('attr-name', 'attr-value');
Related videos on Youtube
Author by
user2282428
Updated on May 22, 2020Comments
-
user2282428 about 4 years
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?
-
Mritunjay almost 10 yearsI think you shouldn't call that function say just
function_name
. -
Florian Gl almost 10 yearsCan't you add an condition in your click function with a boolean value, which is false by default and then set it true where you want to "add" this function?
-
-
Gonçalo Vieira over 8 yearsisn't this DOM manipulation? ie, what you're not supposed to be doing with Angular?
-
SoEzPz over 7 yearsNo, DOM manipulation IS what you are supposed to do when needed. The only requirement is to keep DOM manipulation outside of the controller, and keep it in custom directives.
-
bokkie over 6 yearshe said: "dynamically add attribute to div in controller in angular js". Not angular2 and not in html.
-
bokkie over 6 yearstotally different topic than the op's question
-
user4848830 over 4 yearsThis will work only in debug build. In production build where you have this $compileProvider.debugInfoEnabled(false), $scope will not be available like this.
-
Zain Mohsin about 4 yearsThank you! You're a saviour!