我想使用AngularJS指令實現自定義滾動窗格組件。在以下jsfiddle example我有一個基本原型的例子。AngularJS - 當指令呈現完成時如何查詢DOM
這裏是我的想法的一個模式:
這裏是指令代碼:
myApp.directive('lpScrollPane', function factory() {
return {
restrict: 'A',
replace: true,
transclude: true,
template: '<div class="scrollPaneWrapper"><div class="scrollPane" ng-transclude></div><div class="thumbTrack" ></div></div>',
compile: function (tElement, tAttrs) {
var minHeight = 30;
return function (scope, iElement, iAttrs) {
var thumbTrack = angular.element(iElement.children()[1]);
scope.onScrollHeight = function() {
console.log(iElement.children()[0].scrollHeight);
var H1 = iElement[0].offsetHeight;
var H2 = iElement.children()[0].scrollHeight;
if (H2 > H1) {
var trackHeight = Math.round(minHeight + (H1 - minHeight) * (1 - Math.pow((H2 - H1)/H2, 0.8)));
thumbTrack.css({
display: "block",
height: trackHeight + "px"
});
console.log(H2, H1, trackHeight);
} else {
thumbTrack.css({
display: "none"
});
}
};
scope.$watch(function() {
scope.onScrollHeight();
//setTimeout(scope.onScrollHeight, 100)
});
}
}
};
});
基本上有2次潛水1溢出隱藏和一個具有溢出滾動和另一個div來模仿拇指跟蹤器。
我的目標是監視scrollHeight屬性,然後相應地更改跟蹤器高度。問題是$ watch在DOM呈現之前被觸發,所以顯示和計算跟蹤器時會有延遲。現在,我在watch函數上使用了setTimeout,並且它工作正常(取消註釋行35和註釋34以查看它的行爲)。
什麼是正確的做法?
謝謝你,我會研究它 –