Home > Article > Web Front-end > 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(); } ); } } } )
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!