我试图使一个div在窗口大小调整时自动调整大小,搜索后发现使用指令是最好的解决方案。
模板:
<div elHeightResize ng-view ng-style="{ height: windowHeight }"></div>
指令:
myApp.directive('elheightresize', ['$window', function($window) {
return {
link: function(scope, elem, attrs) {
scope.onResize = function() {
var header = document.getElementsByTagName('header')[0];
elem.windowHeight = $window.innerHeight - header.clientHeight;
}
scope.onResize();
angular.element($window).bind('resize', function() {
scope.onResize();
})
}
}
}])
虽然我可以在scope.onResize
函数中记录elem.windowHeight
,但似乎无法将其应用于ngStyle
。
我还是忽略了什么吗?
编辑:
<div ng-view resize style="height: {{ windowHeight }}px">
这个解决方案似乎有效,但我还是想知道为什么使用ngStyle
不起作用。
elem.windowHeight
不适用于ngStyle
)是,你必须手动应用它,通过触发一个 digest 循环,因为.bind()
方法不被 Angular 拦截。所以在事件处理程序结束后(在scope.onResize(); })
之后),你应该添加scope.$apply();
。 - f.ardelian