我是AngularJS的新手.我已经了解到我可以使用如下查询在DOM中找到元素:
var e = angular.element(document.querySelector('#id'));
var e = angular.element(elem.querySelector('.classname'));
Run Code Online (Sandbox Code Playgroud)
这对于按ID或CSS类名查找元素很有用.但是,我需要能够使用不同的方法找到元素.我有一个如下所示的元素:
<div my-directive class='myContainer'>...</div>
Run Code Online (Sandbox Code Playgroud)
我无法查询'myContainer',因为它重用了多少.出于这个原因,我想找到任何具有属性'my-directive'的元素.如何搜索DOM并找到使用'my-directive'的任何元素?
edd*_*iec 43
而不是查询DOM中的元素(如果我有jQuery背景,那么不是很有角度地看"在AngularJS中思考")你应该在你的指令中执行你的DOM操作.您可以在链接功能中使用该元素.
所以在你的myDirective中
return {
link: function (scope, element, attr) {
element.html('Hello world');
}
}
Run Code Online (Sandbox Code Playgroud)
如果必须在指令之外执行查询,则可以在现代浏览器中使用querySelectorAll
angular.element(document.querySelectorAll("[my-directive]"));
Run Code Online (Sandbox Code Playgroud)
但是你需要使用jquery来支持IE8和向后
angular.element($("[my-directive]"));
Run Code Online (Sandbox Code Playgroud)
或编写自己的方法,如果没有使用库,当querySelectorAll不可用时,按属性获取元素?
Mic*_*mza 11
您的用例不明确.但是,如果您确定需要基于DOM而不是模型数据,那么这是一个指令可以引用所有具有指定的指令的方法.
方式是子指令可以require
是父指令.父指令可以公开一个方法,该方法允许直接指令使用父指令注册其元素.通过这个,父指令可以访问子元素.所以,如果你有一个模板,如:
<div parent-directive>
<div child-directive></div>
<div child-directive></div>
</div>
Run Code Online (Sandbox Code Playgroud)
然后指令可以编码如下:
app.directive('parentDirective', function($window) {
return {
controller: function($scope) {
var registeredElements = [];
this.registerElement = function(childElement) {
registeredElements.push(childElement);
}
}
};
});
app.directive('childDirective', function() {
return {
require: '^parentDirective',
template: '<span>Child directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
parentController.registerElement(iElement);
}
};
});
Run Code Online (Sandbox Code Playgroud)
您可以在http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview上看到此操作
Mic*_*per 11
你还没有说明你在哪里寻找元素.如果它在控制器的范围内,有可能,尽管合唱你会听到它不是'Angular Way'.合唱是正确的,但有时候,在现实世界中,它是不可避免的.(如果你不同意,请联系 - 我对你有挑战.)
如果你$element
像控制器一样进入控制器$scope
,你可以使用它的find()
功能.请注意,在Angular中包含的jQueryLite中,find()
只会按名称而不是属性来定位标记.但是,如果在项目中包含完整的jQuery,find()
则可以使用所有功能,包括按属性查找.
那么,对于这个HTML:
<div ng-controller='MyCtrl'>
<div>
<div name='foo' class='myElementClass'>this one</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
这个AngularJS代码应该工作:
angular.module('MyClient').controller('MyCtrl', [
'$scope',
'$element',
'$log',
function ($scope, $element, $log) {
// Find the element by its class attribute, within your controller's scope
var myElements = $element.find('.myElementClass');
// myElements is now an array of jQuery DOM elements
if (myElements.length == 0) {
// Not found. Are you sure you've included the full jQuery?
} else {
// There should only be one, and it will be element 0
$log.debug(myElements[0].name); // "foo"
}
}
]);
Run Code Online (Sandbox Code Playgroud)