AngularJS访问指令模板中的DOM元素(AngularJS accessing DOM elements inside directive template)
在指令模板中选择DOM元素有更多的“有角度”的方式吗? 例如,说你有这个指令:
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>元素。 有更好的方法吗?
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"); } } });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)元素简单地分配给作用域。
这是指令:
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 不知道这是如何表现明智的You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.
Here is the directive:
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; });Usage:
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 } } });Some remarks:
Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list not sure how this behaves performance-wise
更多推荐
发布评论