0

考虑这个可运行的例子:

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 中的克隆参数将对象作为 .contents() 返回。这将包括文本节点。我有两个问题:

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

1 回答 1

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'));
    }
});

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

于 2014-12-11T11:36:53.130 回答