Javascript AngularJS:如何通过 id 获取 DOM 元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32476623/
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
AngularJS: How to get a DOM element by id
提问by Spikee
Sample
样本
Please consider this Plunkr.
请考虑这个Plunkr。
What I need
我需要的
I need to be able to get an element by it's id.
我需要能够通过它的 id 获取一个元素。
The sample code should be able to assign a css class to any DOM element that exists on the current view.
示例代码应该能够为当前视图中存在的任何 DOM 元素分配一个 css 类。
This should be checked using a source object, provided by the $scope in a controller. This source object may/will have more properties than there are input elements on the view.
这应该使用由控制器中的 $scope 提供的源对象进行检查。此源对象可能/将具有比视图上的输入元素更多的属性。
So I want to loop through each object key and see if a corresponding DOM element exists. If so, validate it's value.
所以我想遍历每个对象键,看看是否存在相应的 DOM 元素。如果是这样,请验证它的值。
The question
问题
How do I get an element by id, using AngularJS only (jQuery is NOT allowed!!)?
如何通过 id 获取元素,仅使用 AngularJS(不允许使用 jQuery!)?
Specifically for the Plunkr, I need this function to (really) work:
特别是对于 Plunkr,我需要这个功能来(真正)工作:
self.IsFieldCurrentlyActive = function(field){
// Should be (in pseudocode):
// var inputElement = angular.find(field);
// return (inputElement != 'undefined');
// Sample only
var idx = field.indexOf('Unused');
return idx == -1;
};
And this one (basically the same):
而这个(基本相同):
self.GetElementByKey = function(key)
{
// Should be (in pseudocode):
// var inputElement = angular.find(field);
// return inputElement;
// Sample only
return null;
}
Update
更新
Apologies, I forgot to add an important requirement: I can't use any mechanism that assumes unique IDs, because there may be multiple occurrences of the same form (and the same IDs). So, I need to respect the Angular scope.
抱歉,我忘了添加一个重要的要求:我不能使用任何假设唯一 ID 的机制,因为可能会多次出现相同的表单(和相同的 ID)。所以,我需要尊重 Angular 范围。
Thanks!
谢谢!
回答by Lauromine
In pure JS you can do document.querySelector('#myID');
在纯 JS 中你可以做 document.querySelector('#myID');
Or within angular using angular.element:
angular.element(document.querySelector('#myID'));
或者在 angular 内使用 angular.element:
angular.element(document.querySelector('#myID'));
回答by Nishith Kant Chaturvedi
Instead try angular.element($('#myElement'));
而是尝试 angular.element($('#myElement'));