窗口大小调整指令 [英] Window resize directive

查看:149
本文介绍了窗口大小调整指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让一个div大小调整时,调整窗口大小,环顾四周后,似乎用一个指令是最好的解决方案。

I was trying to make a div resize when the window resizes, after looking around, it seems that using a directive was the best solution.

模板:

<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();
            })
        }
    }
}])

虽然我可以登录 elem.windowHeight scope.onResize ,它似乎并没有将其应用到 ngStyle

While I can log elem.windowHeight in scope.onResize, it doesn't seem to apply it to ngStyle

我还在忽视的东西?

编辑:

&LT; D​​IV NG视图调整大小的风格=高度:{{WINDOWHEIGHT}} PX&GT;

该解决方案似乎工作,仍然有兴趣了为什么使用 ngStyle 不能正常工作。

This solution seems to work, still interested into why using ngStyle wasn't working.

推荐答案

我想你忘了要火致电范围消化周期$适用(); 末的 scope.onResize

I think you forgot to fire digest cycle by calling scope.$apply(); at the end of scope.onResize method

不管怎么说,我用下面的指令(从了<大骨节病> HERE)这对我的作品:

Anyways, I used following directive (took from HERE) that works for me:

尝试打开调试视图并更改视图高度:演示<大骨节病> 小提琴

Try to open debug view and change view height: Demo Fiddle

app.directive('resize', function ($window) {
    return function (scope, element, attr) {

        var w = angular.element($window);
        scope.$watch(function () {
            return {
                'h': w.height(), 
                'w': w.width()
            };
        }, function (newValue, oldValue) {
            scope.windowHeight = newValue.h;
            scope.windowWidth = newValue.w;

            scope.resizeWithOffset = function (offsetH) {

                scope.$eval(attr.notifier);

                return { 
                    'height': (newValue.h - offsetH) + 'px'
                    //,'width': (newValue.w - 100) + 'px' 
                };
            };

        }, true);

        w.bind('resize', function () {
            scope.$apply();
        });
    }
}); 

和用法:

 <div  ng-style="resizeWithOffset(165)" 
       resize 
        notifier="notifyServiceOnChage(params)"
   >
    /** ... */
 </div>

虚拟控制器使用方法:

$scope.notifyServiceOnChage = function(){
      console.log($scope.windowHeight);   
 };

下面是没有jQuery库的演示使用 innerHeight

Here is demo without jQuery library by using innerHeight

示范3 <大骨节病> 小提琴

Demo 3Fiddle

这篇关于窗口大小调整指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆