AngularJS directive tracks parent resize

Problem

I have a simple directive that updates the sizes for a specific item. This oversees the size of the window and makes the appropriate changes.

MyApp.directive('resizeTest', ['$window', function($window) { return { restrict: 'AC', link: function(scope, element) { var w = angular.element($window); scope.$watch(function() { return { 'h': w.height(), 'w': w.width() }; }, function(newValue, oldValue) { // resizing happens here }, true); w.bind('resize', function() { scope.$apply(); }); } }; }]); 

This works great.

It so happened that inside the div tag with which I am connected, I have a child div . When the size of the parent changes, I want to make positioning changes for the child. However, I can not start the trigger.

It is called at startup, but does not start when the item is resized or the window is changed:

 MyApp.directive('centerVertical', ['$window', function($window) { return { restrict: 'AC', link: function(scope, element) { element.css({border: '1px solid #0000FF'}); scope.$watch('data.overlaytype', function() { $window.setTimeout(function() { console.log('I am: ' + element.width() + 'x' + element.height()); console.log('Parent is: ' + element.parent().width() + 'x' + element.parent().height()); }, 1); }); } }; }]); 

What type of binding or clock configuration should I use to check if the parent element is resized?

Fiddle

https://jsfiddle.net/rcy63v7t/1/

+6
source share
1 answer

The data.overlaytype value that you observe in the centerVertical directive is not specified in scope , so the resulting value is undefined , and this value never changes, so you don't get an executable listener. To check if the size of the parent element has changed, you can check it in the $ watch function as follows:

 scope.$watch( function () { return { width: element.parent().width(), height: element.parent().height(), } }, function () {}, //listener true //deep watch ); 

Also, remember that if you want to use an existing module, you cannot call it that angular.module('myModule', []) because it means creating a new module. You just need to pass the module name angular.module('myModule') , which is secondly why your code is not working.

+10
source

Source: https://habr.com/ru/post/984320/


All Articles