【问题标题】:AngularJS Directive jqLite convert .contents() to .children()AngularJS 指令 jqLit​​e 将 .contents() 转换为 .children()
【发布时间】:2014-12-11 11:13:07
【问题描述】:

考虑这个可运行的例子:

var app=angular.module('myapp', [])
.directive('mydct', function () {
  return {
    restrict:'EA',
    transclude:true,
    template:"<div>Template</div>",
    replace:true,
    scope:true,
    link: function (scope, elm, attrs,ctrl,transcludeFn) {
      transcludeFn( function( clone, scope ) {
        console.log(clone[0]);
        console.log(clone[1]);
        console.log(clone[2]);
        console.log(clone[3]);
        //clone[3].attr('id');
      });
    }
  };
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app='myapp'>
  <mydct>
    <div id='one'>This is one</div>
    <span id='two'>This is two</span>
  </mydct>
</body>

如您所见,transcludeFunction 中的 clone 参数会将对象返回为 .contents()。这将包括文本节点。我有两个问题:

  1. 有没有办法将此内容数组转换为子数组,从而省略文本节点?
  2. 如您所见,我在访问数组中的元素时会取出文本内容,我该怎么做才能将它们作为元素获取,并且能够获取属性?

【问题讨论】:

    标签: angularjs angularjs-directive jqlite


    【解决方案1】:
    transcludeFn( function( clone, scope ) {
        var els, i;
    
        // convert to a normal array
        els = Array.prototype.slice.call(clone);
    
        // exclude text nodes
        els = els.filter(function (element) {
            return element.nodeType !== Node.TEXT_NODE;
        });
    
        // wrap each DOMElement in a jqLite object
        for (i = 0; i < els.length; i++) {
            els[i] = angular.element(els[i]);
        }
    
        for (i = 0; i < els.length; i++) {
            // do what you like with each clone's attribute
            console.log(els[i].attr('id'));
        }
    });
    

    为了强调要执行的步骤,这有点冗长,但可以在必要时简化或缩短代码。

    【讨论】:

    • 天哪,有这么复杂吗?特别是如果您每次从列表中选择一个元素时都必须调用 angular.element?
    • 您在clone 数组中获得的元素默认情况下不是 jqLit​​e/jQuery 包装的,因此如果您想使用 jqLit​​e 方法,那么是的,您必须包装它们。或者,您可以只使用本机 DOM API。比如element.getAttribute('id')获取id属性的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多