AngularJS 访问指令模板内的 DOM 元素 [英] AngularJS accessing DOM elements inside directive template

查看:24
本文介绍了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

    元素.有没有更好的方法来做到这一点?

    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?

    推荐答案

    您可以为此编写一个指令,它只需使用属性给定的名称将 (jqLit​​e) 元素分配给作用域.

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

    这篇关于AngularJS 访问指令模板内的 DOM 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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