Javascript Angularjs 动态设置属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25759497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:50:21  来源:igfitidea点击:

Angularjs dynamically set attribute

javascriptangularjsattributessetattribute

提问by user2282428

I'm trying to dynamically add attribute to div in controller in angular js.

我正在尝试在 angular js 中的控制器中向 div 动态添加属性。

 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?

一切看起来都很好,在调试器中,我看到添加了该属性,但它没有执行我的函数。您对如何向现有 div 添加属性以及如何使其工作有任何想法吗?

采纳答案by cevek

You need to recompile your div

你需要重新编译你的div

var el = angular.element("div_id");
$scope = el.scope();
$injector = el.injector();
$injector.invoke(function($compile){
   $compile(el)($scope)
})

http://jsfiddle.net/r2vb1ahy/

http://jsfiddle.net/r2vb1ahy/

回答by Shaishab Roy

get element by id and set new attribute and value

通过 id 获取元素并设置新的属性和值

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

回答by Navoneel Talukdar

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');

回答by Pavel Chuchuva

Angular2 is providing [attr.<attribute name>]to bind attribute values.

Angular2 提供[attr.<attribute name>]绑定属性值。

<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

来自http://blog.sodhanalibrary.com/2016/02/set-attribute-and-remove-attribute-with.html