AngularJS - 查找具有属性的元素 [英] AngularJS - Find Element with attribute

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

问题描述

我是 AngularJS 的新手.我了解到我可以使用如下查询在 DOM 中查找元素:

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

这对于按 ID 或 CSS 类名查找元素很有用.但是,我需要能够使用不同的方法找到一个元素.我有一个如下所示的元素:

...

我无法查询myContainer",因为它重复使用了多少.出于这个原因,我想找到任何具有my-directive"属性的元素.如何搜索 DOM 并找到任何使用我的指令"的元素?

解决方案

而不是查询 DOM 的元素(这不是很有角度,请参阅 在 AngularJS 中思考"如果我有 jQuery 背景?)你应该执行你的指令中的 DOM 操作.您可以在链接函数中使用该元素.

所以在你的 myDirective 中

return {链接:函数(范围、元素、属性){element.html('你好世界');}}

如果您必须在指令之外执行查询,则可以在现代浏览器中使用 querySelectorAll

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

但是你需要使用 jquery 来支持 IE8 和向后

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

或按照此处所示编写自己的方法 当 querySelectorAll 在不使用库的情况下不可用时按属性获取元素?

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

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>

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'?

解决方案

Rather than querying the DOM for elements (which isn't very angular see "Thinking 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.

So in your myDirective

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

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]"));

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

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

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

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

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