Monitoring changes in the size of the parent element with an AngularJS directive

Issue

I am facing a challenge with a directive that updates the size of an element based on the window size. The directive monitors changes in window dimensions and adjusts the element accordingly.

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 logic here
      }, true);
      w.bind('resize', function() { scope.$apply(); });
    }
  };
}]);

The implementation works correctly as expected.

In my code, I have a parent div element with a child div. I aim to adjust the position of the child element when the parent is resized. However, I am unable to trigger the necessary actions for this.

Despite being called initially, the following code does not respond to resizing events:

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 kind of binding or watch configuration should be used to detect resizing of the parent element?

Interactive Example

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

Answer №1

When observing the value data.overlaytype in the centerVertical directive, it's important to note that it is not on the scope. As a result, the value will be undefined and won't change, leading to the listener not being executed. To monitor changes in the size of the parent element, you can use the following code within the $watch function:

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

It's also crucial to remember that when using an existing module, you should not create a new one with angular.module('myModule', []). Instead, simply pass the module name like angular.module('myModule'). This could have been another reason why your code was not functioning as expected.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Sending post parameters from Angular and receiving JSON data from PHP using $http

Exploring the world of Angular and delving into the realm of $http, I find myself faced with a perplexing challenge: How to post parameters using $http (necessary for PHP to execute the call) Retrieve a JSON response from that call Here's what I&ap ...

Utilize Material-UI slider components to dynamically manage slider handles

I am trying to dynamically create sliders based on user input and struggling with saving values when they are changed. Below is the code snippet I have implemented so far. The issue I'm facing is that I cannot retrieve the value using event.target.val ...

Callback in React Setstate triggered, leading to a delay in rendering

Recently, I embarked on a journey to learn React just 2 days ago. Despite my enthusiasm, I have encountered some challenges with React's setState method. As far as my understanding goes, I should utilize the prevState parameter when I need to alter th ...

How to send cross-domain AJAX requests to RESTful web services using jQuery?

I have been utilizing Jquery Ajax calls to access RESTful webservices in the following manner. The web service is being hosted on a different domain. $.ajax({ type: "GET", url: "url for the different domain hosting", crossDomain: true, ...

The response from Moment.js shows the date as "December 31, 1969."

Currently, I am in the process of recreating one of FCC's backend projects: Upon testing my code, I noticed that when I input the following URL: http://localhost:3000/1 The result is as follows: {"unix":"1","natural":"December 31, 1969"} var e ...

Using a prop array as v-model in a Vue JS CheckBoxGroup implementation

Struggling to create a reusable CheckBoxGroup component with a prop array as v-model. I checked out the vuejs guide at https://v2.vuejs.org/v2/guide/forms.html#Checkbox which uses the v-model array in the data of the same component. However, this approach ...

Performing a consistent influx of data into a MySQL database using Node.js encounters an issue: "Unable to enqueue Handshake as a Handshake has

I am trying to insert values into a database in a continuous manner. Here is the code I have attempted: var mysql = require("mysql"); const random = require("random"); var con = mysql.createConnection({ host: "xxx", user: "xxx", password: "xxx", ...

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

"Exploring the World of ASP.NET VB: A Beginner's Guide to

Attempting to call a web service using JS from an ASP.NET website (VB) client side. Although familiar with web services, setting one up is new territory for me. Looking to implement async updates and queries. Any assistance, examples, or best practices wou ...

React: maintaining referential equality across renders by creating closures with useCallback

I want to make sure the event handling function I create in a custom hook in React remains referentially equal across renders. Is it possible to achieve this using useCallback without specifying any variables it closes over in the dependencies list? Will o ...

Utilizing JQuery's $(document).ready() function following a window.location change

I'm having trouble getting a JavaScript function to run after being redirected to a specific page like "example.com" when the DOM is ready for it to work with. Unfortunately, it seems that $(document).ready() is running before "example.com" finishes l ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

The OrderBy feature may not apply to the initial items being displayed in an ng-repeat loop

Curiously, when attempting to sort by name on an object array, the first 10 or so objects appear random before the orderBy function works correctly. Any suggestions on how to address this issue? Appreciate any assistance! ...

Is it possible to have setTimeOut() executed after the page has been redirected?

Why is it not possible to duplicate: The question was not addressed in the previous post. I have a link for deletion, which, when clicked, triggers a popup with a button. Upon clicking that button, the page inside the popup redirects to a new internal pag ...

Gruntjs Live Reload is actively monitoring for changes, yet fails to refresh the page

Check out my Gruntfile.js here Also, take a look at my package.json here I ran npm install in the main directory of my workspace (using WAMP) and it created a node_modules folder along with several subfolders. After navigating to the directory c:\w ...

What is the purpose of $ and # in the following code snippet: $('#<%= txtFirstName.ClientID%>')

$('#<%= txtFirstName.ClientID%>').show(); Attempting to pass the ClientId as a parameter from server tags to an external JavaScript file. <input type="text" ID="txtFirstName" runat="server" maxlength="50" class="Def ...

Tips on incorporating asynchronous functionality in AngularJS

I am currently utilizing AngularJS version 1.5.8 and have a specific requirement. When the user clicks on the Next button, the text inside the button should change to 'Processing...' before completing the operation. I have implemented the $q serv ...

What is the best way to alternate between displaying HTML content with v-html and plain text in Vue.js?

I need a way to switch between v-html and plain text in Vue.js v2. Here's what I have so far: HTML <div id="app"> <h2 v-html="html ? text : undefined">{{html ? '' : text}}</h2> <button @click=&qu ...

When selecting an option triggers a pop-up in JavaScript

Implementing javascript and HTML. Consider this example: <select name='test' > <option value='1'> <option value='2'> <option value='3'> </select> If the user selects optio ...