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

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

推荐答案

您可以为此编写指令,该指令仅使用属性名将(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
        }
    }
});

一些评论:

  • 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天全站免登陆