我是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
};
})