Angularjs dynamically set attribute
Asked Answered
S

4

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?

Seizing answered 10/9, 2014 at 7:21 Comment(2)
I think you shouldn't call that function say just function_name.Filibeg
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?Folsom
C
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/

Carlitacarlo answered 10/9, 2014 at 7:32 Comment(2)
This will work only in debug build. In production build where you have this $compileProvider.debugInfoEnabled(false), $scope will not be available like this.Ephemera
Thank you! You're a saviour!Mannose
A
17

get element by id and set new attribute and value

 var el =angular.element('#divId');
 el.attr('attr-name', 'attr-value');
Atwood answered 25/6, 2015 at 7:55 Comment(2)
isn't this DOM manipulation? ie, what you're not supposed to be doing with Angular?Zalea
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.Elodea
M
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');
Magill answered 19/2, 2016 at 18:23 Comment(1)
totally different topic than the op's questionInkerman
W
-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

Wimbush answered 21/5, 2017 at 20:53 Comment(1)
he said: "dynamically add attribute to div in controller in angular js". Not angular2 and not in html.Inkerman

© 2022 - 2024 — McMap. All rights reserved.