AngularJS:更好的方式来观看的高度变化 [英] AngularJS: Better way to watch for height change

查看:140
本文介绍了AngularJS:更好的方式来观看的高度变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在老可变高度导航的问题:A 位置:在顶部修复导航和的margin-top内容:$ naviHeight 下面。
当数据异步加载等内容的保证金与它改变了导航可以改变高度。

I'm having the old variable height navigation problem: A position: fixes navigation on top and a content with margin-top: $naviHeight below. The navigation can change height when data is loaded asynchronously and so the content's margin has to change with it.

我希望这是自包含的。因此,没有code,其中的数据加载,但只有在所涉及的HTML元素/指令。

I want this to be self contained. So no code where the data is loaded but only in the involved html-elements/directives.

目前我正与这样一个计时器做在AngularJS 1.2.0

Currently I'm doing it in AngularJS 1.2.0 with a timer like this:

/*
* Get notified when height changes and change margin-top
 */
.directive( 'emHeightTarget', function(){
    return {
        link: function( scope, elem, attrs ){

            scope.$on( 'heightchange', function( ev, newHeight ){

                elem.attr( 'style', 'margin-top: ' + (58+newHeight) + 'px' );
            } );
        }
    }
})

/*
* Checks this element periodically for height changes
 */
.directive( 'emHeightSource', ['$timeout', function( $timeout ) {

    return {
        link: function( scope, elem, attrs ){

            function __check(){

                var h = elem.height();

                if( h != scope.__height ){

                    scope.__height = h;
                    scope.$emit( 'heightchange', h );
                }
                $timeout( __check, 1000 );
            }
            __check();
        }
    }

} ] )

这有利用定时器(我觉得有点丑)和,直到内容被移动调整导航经过一定的延迟明显的缺点。

This has the obvious drawback of using the timer (which i feel kind of ugly) and a certain delay after the navigation resized until the content is moved.

有没有更好的方法来做到这一点?

Is there a better way to do this?

推荐答案

这工作由 emHeightSource 注册一个观察者被称为每 $消化。它更新 __高度属性而这又是在 emHeightTarget 观看视频:

This works by registering a watcher in emHeightSource which is called every $digest. It updates the __height property which is in turn watched in emHeightTarget:

/*
 * Get notified when height changes and change margin-top
 */
.directive( 'emHeightTarget', function() {
    return {
        link: function( scope, elem, attrs ) {

            scope.$watch( '__height', function( newHeight, oldHeight ) {
                elem.attr( 'style', 'margin-top: ' + (58 + newHeight) + 'px' );
            } );
        }
    }
} )

/*
 * Checks every $digest for height changes
 */
.directive( 'emHeightSource', function() {

    return {
        link: function( scope, elem, attrs ) {

            scope.$watch( function() {
                scope.__height = elem.height();
            } );
        }
    }

} )

这篇关于AngularJS:更好的方式来观看的高度变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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