AngularJS: Better way to watch for height change

Question!

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.

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

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?

By : Scheintod


Answers

This approach watches an elements height and width and assigns it to a variable on the scope provided on your elements attribute

 


This video can help you solving your question :)
By: admin