"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can AngularJS $watch Replace Timers in Dynamic Navigation Height Adjustment?

How Can AngularJS $watch Replace Timers in Dynamic Navigation Height Adjustment?

Published on 2024-11-05
Browse:139

How Can AngularJS $watch Replace Timers in Dynamic Navigation Height Adjustment?

Avoiding Timers in Height Watching for AngularJS

AngularJS programmers often face the challenge of responsive navigation when the navigation height is dynamic. This leads to the requirement for adjusting the content's margin-top value in response to navigation height changes.

Previously, a timer was used to detect navigation height changes, but this approach had drawbacks: the use of a timer and a delay in adjusting the content's margin-top.

Fortunately, a better approach exists: leveraging AngularJS's $watch functionality. Instead of a timer, a watcher is registered in 'emHeightSource,' which is invoked during each $digest cycle. The watcher updates the '__height' property.

In 'emHeightTarget,' another watcher monitors '__height' and updates the margin-top value accordingly, ensuring that the content's margin-top changes smoothly and in sync with the navigation height.

Here is the refined code using watchers:

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

} )
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3