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?

2
  • 1
    I think you shouldn't call that function say just function_name. Commented Sep 10, 2014 at 7: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? Commented Sep 10, 2014 at 7:24

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

1 Comment

This will work only in debug build. In production build where you have this $compileProvider.debugInfoEnabled(false), $scope will not be available like this.
17

get element by id and set new attribute and value

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

2 Comments

isn't this DOM manipulation? ie, what you're not supposed to be doing with Angular?
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.
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');

1 Comment

totally different topic than the op's question
-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

1 Comment

he said: "dynamically add attribute to div in controller in angular js". Not angular2 and not in html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.