我是AngularJS的新手,有一個問題,我希望有人能指出我正確的方向來搞清楚。我創建了一個名爲sizeWatcher
的指令,該指令作爲一個屬性放置到HTML中,它基本上只是獲取其所在元素的高度,並將該高度反饋到名爲style
的作用域變量中,該變量通過使用ng-style="style"
設置到另一個元素上。角度指令多次觸發
我發現無論何時我打開手風琴,$watch
都會觸發該指令,但它會發射多次。我有一個console.log
在我的$watch
,我看到3個日誌條目,前兩個是相同的(猜測這發生在手風琴打開前點擊,然後手風琴打開,第三個日誌條目是手風琴打開後的最終高度)。主要問題是style
變量在手風琴被展開之前只能設置到較小的高度,即使日誌在最後一次命令被擊中時記錄的高度更高 - 我怎樣才能忽略第一個事件觸發和只有在指令的最後一次和最後一次執行時才採取相應措施?任何洞察到這一點將不勝感激。下面的相關代碼附:
模板:
<div class="content-wrap" id="height-block" ng-style="style">
<!-- Other HTML etc... -->
<uib-accordion size-watcher close-others="oneAtATime">
<!-- Accordion Directive HTML.. -->
</uib-accordion>
</div>
的JavaScript:
.directive("sizeWatcher", function() { //add size-watcher attribute to element on the page to have it echo its' height to the {{style}} scope
function link(scope, element, attrs) {
scope.$watch(function() { //watch element for changes
var height = element[0].offsetHeight;
console.log(height);
if (height > 150) {
scope.style = {
height: height + 'px'
};
}
});
}
return {
restrict: "AE", //attribute & element declarations
link: link
};
})