2015-06-17 48 views
4

使用AngularJS,我試圖在指令中的 scrollHeight一個元素(隱藏在兩個表內)。這種行爲很奇怪;值首次改變時,它會觸發我的功能。它沒有,然後它爲好第二次...

scrollHeight我看是雙表內:

<table> 
    <tbody> 
    <tr> 
     <td ng-click="show()" style="cursor:pointer">Show Row</td> 
    </tr> 
    <tr> 
     <td> 
     <table ng-show="showRow"> 
      <tbody> 
      <tr> 
       <td ng-click="showTD()" style="cursor:pointer">Show Cell</td> 
      </tr> 
      <tr ng-show="showCell"> 
       <td id="tracker" tracker=""> Watch that</td> 
      </tr> 
      </tbody> 
     </table> 
     </td> 
    </tr> 
    </tbody> 
</table> 

而我的指令,看它:

myApp.directive('tracker', function() { 
    return { 
    compile : function(elem, attr, linker) { 
     return function(scope, elm, attrs) { 
      scope.$watch(function(){ return elm[0].scrollHeight }, function(){ 
      console.log(elm[0].scrollHeight); 
      }); 
     }; 
    } 
    } 
}); 

我做了一個plunker來說明這種行爲。如果你打開控制檯,你會看到以下內容:

  • 我看了細胞得到初始化,你先去scrollHeight(29)
  • 你點擊「顯示行」和元素在您的控制檯獲取顯示(所以你可以檢查scrollHeight值)和$watch被觸發並顯示更新的值(0) - 這是正確的,元素的scrollHeight是0
  • 現在你點擊'顯示單元格',你得到元素scrollHeight已更改(29)),但$ watch不會觸發該功能!?! - 只有當你再次點擊「顯示單元格」時,它纔會被觸發並顯示錯誤的值29!

我需要檢測,只要我的'觀看'被顯示,但因此,這是不可能的。

回答

1

你可以使用ng-if代替ng-show將到特殊,添加和刪除DOM會改變運行後消化週期看消化週期,&被調用,那麼元素的高度計算正確。

標記

<table ng-show="showRow"> 
    <tbody> 
     <tr> 
      <td ng-click="showTD()" style="cursor:pointer">Show Cell</td> 
     </tr> 
     <tr ng-if="showCell"> 
      <td id="tracker" tracker=""> Watch that</td> 
     </tr> 
    </tbody> 
</table> 

Demo Plunkr

+0

非常有趣!你知道爲什麼它不適用於ng-show嗎? – ncohen

+0

@ncohen我添加了簡短描述..通過'ng-if'添加和刪除DOM運行摘要手錶被調用並且高度得到了正確反映 –

+0

好的,但是爲什麼ng-show不起作用?任何想法? – ncohen