Utilizing the power of AngularJS with ng-class for dynamic styling and

I recently started learning AngularJs and I have a question about how angular handles the ng-class attribute.

While working with external libraries for visualization, charts, etc., I often need to trigger the resize event:

window.dispatchEvent(new Event('resize'));

For example: Charts inside a container that changes size when in fullscreen mode, or charts within a modal dialog...

When I try something like this in my controller:

$scope.fullscreen = true;
window.dispatchEvent(new Event('resize'));
console.log($('#mycontainer').height());

And in my template:

<style>
  #mycontainer {
    width: 100px;
    height: 100px;
    background-color: orange;
    color: white;
  }

  .fullscreen {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 99;
  }
</style>

(...)

<div id="mycontainer" ng-class="{'fullscreen': fullscreen}">
  content here
</div>

The console.log statement prints the old size without applying the fullscreen class.

Is there a way to render the ng-class inside a controller or forcefully apply a class without using the JQuery .addClass method?

Fiddle example: https://jsfiddle.net/Garet/d9c7ux3j/2/

Answer №1

Hey there! If you're having trouble with the DOM rendering, try adding a timer break like this:

  var myapp = angular.module('myapp', []);

    myapp.controller('myctrl', function ($scope) {
   $scope.fullscreen = false;    
   $scope.toggleFullscreen = function() {
   $scope.fullscreen = true;
   window.dispatchEvent(new Event('resize'));
     console.log('before render:');
   console.log($('#mycontainer').height())

    setTimeout(function(){  console.log('after render:');
    console.log($('#mycontainer').height());})
 }
});

Just to note: You don't necessarily need to set it for 1 second, as setTimeout will only execute once the DOM has finished rendering.

Check out your updated fiddle here: https://jsfiddle.net/gdabrz5x/

Answer №2

When using jQuery to retrieve the height of an element, it is important to wait until the element has finished updating its height.
Simply add a brief delay of 1ms after making changes to ensure that the height has been updated.

setTimeout(function(){
   console.log($('#mycontainer').height())
}, 1)

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

Unusual behavior in a for loop with node.js

Trying out some new things with node.js and running into issues with a basic for loop... for (var i = 0; i < 5; i++); {( console.log(i)) } Can anyone explain why I'm seeing 5 in the console? I was anticipating 0,1,2,3,4... ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Tips for fixing the error message "Unhandled Promise Rejection: TypeError: response.body.forEach is not a function" in Vue.js 2

Here is how my Vue.js component looks: <script> export default{ name: 'CategoryBsSelect', template: '\ <select class="form-control" v-model="selected" required>\ <option v-for="option in opt ...

Executing webpack with specific settings in Node.js

In my current package.json file, I have a script defined as follows: "build": "webpack --inline --colors --progress --display-error-details --display-cached", Additionally, there is a webpack.config.js file located at the root of my repository. To strea ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Having trouble with updating a Firebase database object using snap.val()

I'm trying to figure out how to update a property within the snap.val() in order to make changes to my Firebase database. function updateListItem(listItem) { var dbRef = firebase.database() .ref() .child('userdb') .child($sco ...

Exploring the integration of Vue.js and Requirejs for efficient development

After creating a new Vue.js project with vue-cli and building it using the command: vue build --target lib --name myWidget src/main.js I needed to utilize Requirejs for loading: <script> requirejs.config({ paths: { ...

VueJS throws an error when trying to access the 'settings' property of an undefined object

I'm encountering an issue with my basic input in a Vue component. The input should update data on change, but instead I'm getting the error message Uncaught TypeError: Cannot read property 'settings' of undefined Vue component <templ ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

Tips on how to efficiently wrap content within a column layout, and to seamlessly shrink it if necessary

I recently encountered an issue where I am attempting to create a three-column layout with each column filled with a dynamic number of divs (boxes) ranging from 5 to 15, each with its own height based on its content. These divs are expected to: 1) Be dis ...

JavaScript's includes method fails to verify input against the array

Just starting out with Javascript and striving to write clean code! To test my app, I aim to have a user's name input via prompt checked against an array for validation purposes. When I hardcode the value of a variable, the includes function filters ...

Notify user before exiting the page if there is an unsaved form using TypeScript

I am working on a script that handles unsaved text inputs. Here is the code for the script: export class Unsave { public static unsave_check(): void { let unsaved = false; $(":input").change(function(){ unsaved = true; ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

How to automatically insert a page break after a certain string in an array using JavaScript

I've created a code that is intended to implement page breaks after a specific number of new lines or words. I have defined an array that indicates where these breaks should occur within my element. In the example provided in my jsFiddle, you can see ...

Is there a way to detect when a user is interacting with a form item using Vue and Buefy?

I'm interested in activating an event when a user focuses on a form element created using Vue / Buefy. As a newcomer to this, I would appreciate any guidance on how to accomplish this triggering action. ...

Webpack is mistakenly duplicating module loading

I've been working on my angular.js application using webpack for building, and came across an interesting issue. Take a look at this simple example: app.js var angular = require('exports?window.angular!angular'), angularMoment = requir ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. https://i.sstatic.net/aAvVW.jpg H ...

Having trouble with the find method when trying to use it with the transform

In my code, I have three div elements with different values of the transform property assigned to them. I store these elements in a variable using the getElementsByClassName method and then try to find the element where the value of the transform property ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...