Angularjs dynamically set attribute

2019-01-11 17: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?

4条回答
唯我独甜
2楼-- · 2019-01-11 18:00

get element by id and set new attribute and value

 var el =angular.element('#divId');
 el.attr('attr-name', 'attr-value');
查看更多
相关推荐>>
3楼-- · 2019-01-11 18:16

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');
查看更多
走好不送
4楼-- · 2019-01-11 18:17

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/

查看更多
够拽才男人
5楼-- · 2019-01-11 18:26

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

查看更多
登录 后发表回答