tElement vs iElement

时间:2017-06-09 10:22:27

标签: javascript angularjs

我对指令编译和链接函数中的元素的引用感到困惑。

如果没有使用ng-if或ng-switch指令,则这两个函数具有相同的参考元素。但是,如果我使用ng-if / ng-switch,即使它们引用同一个对象,它们也不再是相同的引用。

此外,对于我在编译期间保存的元素的所有其他引用也会发生同样的情况(使用ng-if / ..它们是无用的)。 我设法通过将所有引用移到链接阶段来解决问题,但我想了解背后的原因。

我做了一个小小的演示:



angular.module('demo', [])
  .directive('direc', function() {
    return {
      compile: function(tElement) {
        return function($scope, iElement) {
          console.dir(tElement, iElement);
          iElement.text((tElement === iElement) ? 'true' : 'false');
        };
      }
    };
  });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>

<div ng-app="demo">
  Without ng-if : compile(Element) === link(Element) : <direc></direc>
  </br>
  With ng-if : compile(Element) === link(Element) :  <direc ng-if='true'></direc>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

When we look at official angularjs doc.

iElement - instance element - The element where the directive is to be used.

tElement - template element - The element where the directive has been declared.

and, when you use ng-if or ng-switch both creates new child scope., and new element gets created. So tElement and iElement are not same.,

So in new scope case when you do debugging in broswer console you could see the tElement in case of ng-if bound to document only, whereas iElement is bound to current instance element.(check in ELement tab of chrome)

So you can use ng-show which doesn't create new child scope to achieve same.

See this fiddle, and observe the difference in scope and instance binding.