26

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?

user2282428
  • 295
  • 1
  • 3
  • 6
  • 1
    I think you shouldn't call that function say just `function_name`. – Mritunjay Sep 10 '14 at 07:24
  • 1
    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? – Florian Gl Sep 10 '14 at 07:24

4 Answers4

21

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/

cevek
  • 862
  • 1
  • 7
  • 16
17

get element by id and set new attribute and value

 var el =angular.element('#divId');
 el.attr('attr-name', 'attr-value');
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
  • 1
    isn't this DOM manipulation? ie, what you're not supposed to be doing with Angular? – Gonçalo Vieira Nov 17 '15 at 15:38
  • 4
    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. – SoEzPz Feb 01 '17 at 21:24
0

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');
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42
-1

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

Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115
  • 2
    he said: "dynamically add attribute to div in controller in angular js". Not angular2 and not in html. – bokkie Mar 21 '18 at 15:44