AngularJS - 寻找元素与属性 [英] AngularJS - Find Element with attribute

查看:227
本文介绍了AngularJS - 寻找元素与属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来AngularJS。我知道我可以找到使用类似以下查询的DOM元素:

I'm new to AngularJS. I've learned that I can find elements in the DOM using queries like the following:

var e = angular.element(document.querySelector('#id'));
var e = angular.element(elem.querySelector('.classname'));

这是寻找由ID的元素,或者通过CSS类名是有用的。然而,我需要能够找到用一种不同的方法的元件。我有如下所示的元素:

This is useful for finding elements by ID, or by CSS class name. However, I need to be able to find an element using a different approach. I have an element that looks like the following:

<div my-directive class='myContainer'>...</div>

我不能,因为多少它的重复使用myContainer中查询。出于这个原因,我想找到属性'我的指示性的元素。如何搜索DOM和发现,利用对元素的我-指令?

I can't query on 'myContainer' because of how much its reused. For that reason, I would like to find any element with the attribute 'my-directive'. How do I search the DOM and find any element that makes use of 'my-directive'?

推荐答案

而不是查询为元素的DOM(这是不是很角度看<一个href=\"http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background?rq=1\">How我&QUOT;认为AngularJS&QUOT;如果我有一个jQuery的背景)您应将指令中执行的DOM操作?元素是提供给您在您的链接功能。

Rather than querying the DOM for elements (which isn't very angular see How do I "think in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

因此​​,在您myDirective

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

如果您必须执行该指令的查询外,然后将有可能在现代browers使用querySelectorAll

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

不过,你需要使用jQuery支持IE8和向后

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

或此<一个证明写你自己的方法href=\"http://stackoverflow.com/questions/9496427/how-to-get-elements-by-attribute-selector-w-native-javascript-w-o-queryselector\">How获得通过属性选择元素瓦特/本地JavaScript W / O querySelectorAll

这篇关于AngularJS - 寻找元素与属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆