Implement the scope change in an Angular controller by utilizing controllerAs functionality

I am facing an issue with my controller setup as shown below:

angular
  .module('app.core')
  .controller('TestController', TestController);

TestController.$inject = ['$timeout', '$interval'];

function TestController($timeout, $interval) {

  var vm = this;
  vm.formHeight = '0px';

  $timeout(function() {
    var heightCheck = $interval(function() {
      var formHeightNew = document.getElementById('form').offsetHeight;
      vm.formHeight = formHeightNew + 'px';
    }, 500);
  }, 2000);

};

An interval is triggered after a delay of 2000ms (inside the timeout function) and then runs every 500ms. It updates the view model but the changes are not reflected in the HTML. How can I apply these updates?

I have attempted using vm.$apply() and injecting $scope followed by using $scope.$apply(), but unfortunately, these methods did not work.

In the HTML, I am simply binding the variable to an ngStyle attribute like this (where the controllerAs value is set to 'test'):

<div class="form-wrapper" ng-style="{'height': test.formHeight}">
</div>

The initial value bound to '0px' works fine, however, any subsequent updates do not reflect in the view.

Answer №1

Give this a try

angular
  .module('app.core')
  .controller('TestController', TestController);

TestController.$inject = ['$scope', '$timeout', '$interval'];

function TestController($scope, $timeout, $interval) {

  $scope.formHeight = '0px';

  $timeout(function() {
    var heightCheck = $interval(function() {
      var formHeightNew = document.getElementById('form').offsetHeight;
      $scope.formHeight = formHeightNew + 'px';
    }, 500);
  }, 2000);

};

Also, here is the corresponding HTML code

<div class="form-wrapper" ng-style="{'height': formHeight}">
</div>

Answer №2

This specific snippet of code is designed to efficiently update every half of a second and incorporate new height values:

    <div class="testCtrl" data-ng-controller="appController as test">
        <form action="state1_submit" id="form" method="get" accept-charset="utf-8" >
            <input type="text" name="" value="" >
            <div class="form-wrapper" ng-style="{'height': test.formHeight}">
            </div>
        </form>
    </div>

angular.module('myApp')
    .controller('appController', appController);

function appController($timeout, $interval) {
    var vm = this;
    vm.formHeight = '0px';
    $timeout(function() {
        var heightCheck = $interval(function() {
            var formHeightNew = document.getElementById('form').offsetHeight;
            vm.formHeight = formHeightNew + 'px';
            console.log(vm.formHeight);
            console.log('update');
        }, 500);
    }, 2000);
}

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

Transmit information to Angular application upon being delivered by Express

I am currently working on an Angular application powered by Express 4.0. I am looking to send data to the front end during startup, specifically when the index file is being served. However, I am struggling to determine the most appropriate route to accomp ...

Can the coordinates in an array be constrained within a specific radius?

I am relatively new to using Google Maps and ReactJS. To plot my map, I am utilizing google-maps-react. The property I am working with is comprised of multiple polygons that collectively form the property (farm) displayed on the map. Upon clicking a spec ...

What is the best way to download a vast number of files with nodejs?

I have a total of 25000 image links that I need to download to my local machine using the request package in nodejs. It successfully downloads up to 14000 to 15000, but then I start encountering errors. Error { Error: socket hang up at TLSSocket.onHa ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

Exploring Ways to Retrieve Property Names in AngularJS JSON

I need help finding a way to use the property name as the table header in my code example below: <table> <th ng-repeat="auditorium in auditoriums"> {{ auditorium.NAME }} </th> <tbody ...

Update the getJSON filter to only include specific results and exclude the majority

In an effort to streamline my chart to only include data for "zelcash", I am currently faced with the issue of fluctuating values causing the line graph to be inconsistent. This is because the results show zelcash with 0 as the hashrate, along with actual ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Angular's radio button is set to "checked" on a pre-configured model

Looking for help with customizing alignment of images in a bootstrap/angular template? Check out the code snippet below: <div ng-repeat="a in attributes"> <div class="btn-group" data-toggle="buttons"> <label class="btn btn-white ...

Creating plugin-based applications using HTML5

I am new to developing web applications and want to create an HTML5 cross-platform application that resembles the startup page of Windows 8, displaying multiple windows for users to choose from. I need guidance on how to start this project. I would like ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

Is it possible to incorporate a label within a dropdown menu (<select>)?

How can I add a label inside a select box using Bootstrap? Here is an example: Before selecting an option After selecting an option, the label should appear in a small size like this: After selecting an option : <div class="form-group"> & ...

Encoding multiple arrays in JSON using Zend PHP

I'm encountering an issue with the JSON functionality in Zend and JavaScript. Initially, I attempted to encode a single array that contained a certain number of models in the following manner: echo json_encode(Application_Model_Marker::getMarkers()) ...

How to Retrieve Variables from a Separate .json File in Python

Seeking Assistance I am looking for a way to access variables from an external .json file located in the same directory using Python 2.7. (Import statement is not working for me) The goal is to store the variables in the .json file as shown below: valu ...

The test that utilizes MemoryRouter to render a component with required parameters is failing, showing the error message 'role: heading not found'

Currently, I am working on writing unit tests for the Profile component. This component includes a userParams() function to retrieve the userID from the path variable in order to display the user's information in a profile format. During testing, I u ...

Choose a Vue filter according to the variable selected

My Current Table Dilemma Creating a table from a 2D array in Vue2 has been successful for me, as I've managed to display all the values correctly. However, I am facing issues with formatting. The template code is structured like this: <table> ...

Learn how to dynamically update a user's profile picture in the navbar when clicked using Angular

When I have a navbar (see code below) and set *ngIf = "user", I attempt to display the user's avatar in the navbar but only see a placeholder. However, after refreshing the page, the user avatar appears. Therefore, I am curious about how I can refresh ...

A directive in Angular that leverages the same model but presents varying data

I'm currently developing a custom directive for pagination to be used in two different places on my page. The goal is to have the same pagination directive for two tables of data. Below is the code snippet for the directive: app.directive('pagin ...

What methods are available for retrieving specific XML entries using JavaScript?

Hey there, I'm dealing with this XML code <book> <bookname>book1</bookname> <author>authorman</author> </book> <book> <bookname>book2</bookname> <author>authorperson</author> </book ...

Develop a descriptive box for a radio button form using jQuery

I am working on creating a form with simple yes/no questions. If the answer is no, no explanation is needed. However, if the answer is yes, I want to insert a new table row and display a textarea for an explanation. To ensure data validation, I am utilizi ...

Maintain browser tab state when refreshing using Bootstrap

I have a different HTML page loaded in each tab, and I want to keep the active tab highlighted even after a page refresh using Bootstrap if possible. <div> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#T ...