使用 AngularJS,我试图在指令中 $watch
元素(隐藏在两个表中)的 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!
我需要检测何时显示我的“Watch that”,但正因为如此,这是不可能的。
最佳答案
您可以使用 ng-if
而不是 ng-show
,添加和删除 DOM 将改变运行摘要周期,并且在摘要周期 watch 获取之后调用,然后正确计算元素的高度。
标记
<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>
关于javascript - $watch 第二次值改变时没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901635/