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

Barbara Streisand
Release: 2024-11-02 11:06:30
Original
368 people have browsed it

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

} )
Copy after login

The above is the detailed content of How Can AngularJS $watch Replace Timers in Dynamic Navigation Height Adjustment?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!