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)
})

http://jsfiddle.net/r2vb1ahy/

Solution 2

get element by id and set new attribute and value

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

Related videos on Youtube

user2282428
Author by

user2282428

Updated on May 22, 2020

Comments

  • user2282428
    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
      Mritunjay almost 10 years
      I think you shouldn't call that function say just function_name.
    • Florian Gl
      Florian Gl almost 10 years
      Can'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
    Gonçalo Vieira over 8 years
    isn't this DOM manipulation? ie, what you're not supposed to be doing with Angular?
  • SoEzPz
    SoEzPz over 7 years
    No, 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
    bokkie over 6 years
    he said: "dynamically add attribute to div in controller in angular js". Not angular2 and not in html.
  • bokkie
    bokkie over 6 years
    totally different topic than the op's question
  • user4848830
    user4848830 over 4 years
    This 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
    Zain Mohsin about 4 years
    Thank you! You're a saviour!