本文介绍了AngularJS访问指令模板内的DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在指令模板内选择DOM元素是否有更折角"的方式?例如,假设您有以下指令:
Is there a more "angular" way of selecting DOM elements inside a directive template? For example, say you have this directive:
app.directive("myDirective", function() {
return {
template: '<div><ul><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
我使用jQuery样式选择器来保留模板中呈现的DOM <ul>
元素.有更好的方法吗?
I used the jQuery style selector to get a hold of the DOM <ul>
element rendered in my template. Is there a better way to do this?
推荐答案
您可以为此编写指令,该指令仅使用属性名将(jqLite)元素分配给作用域.
You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
这是指令:
app.directive("ngScopeElement", function () {
var directiveDefinitionObject = {
restrict: "A",
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) {
scope[iAttrs.ngScopeElement] = iElement;
}
};
}
};
return directiveDefinitionObject;
});
用法:
app.directive("myDirective", function() {
return {
template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
link: function(scope, element, attrs) {
scope.list[0] // scope.list is the jqlite element,
// scope.list[0] is the native dom element
}
}
});
一些评论:
- 由于嵌套指令的编译和链接顺序您只能从
myDirective
的postLink-Function中访问scope.list
,您仍然很可能会使用它 -
ngScopeElement
使用preLink函数,因此嵌套在具有ng-scope-element
的元素中的指令可以访问scope.list
- 不确定性能如何表现
- Due to the compile and link order for nested directives you can only access
scope.list
frommyDirective
s postLink-Function, which you are very likely using anyway ngScopeElement
uses a preLink-function, so that directives nested within the element havingng-scope-element
can already accessscope.list
- not sure how this behaves performance-wise
这篇关于AngularJS访问指令模板内的DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!