The ng-model failed to display the updated value until a click was made somewhere on the page

I am struggling with displaying the correct value of an ngModel variable defined in my controller. Despite changing to the correct value in the console, it doesn't update on the page until I click somewhere else or hit the update button again.

Here's a snippet from my themeLayout.html file:

<div class="theme-body" ng-controller="ThemeController as theme">
  <select ng-model="theme.selectedTheme" ng-change="theme.getThemeDetails(theme.selectedTheme)">
    <option ng-repeat="option in theme.themePacks">{{option.title}}</option>
  </select>
  <div class="form-group">
    <label for="appLogo">App Logo</label>
    <div>
      <img ng-src="{{theme.currentThemeImageUrl}}" alt="Description" />
    </div>
    <input type="text" class="form-control" id="appLogo" ng-model="theme.currentThemeImageUrl">
  </div>
</div>

And here is a snippet from my theme controller:

export default class ThemeController {
      constructor($log, ApiService, $scope, $state, $window) {
        'ngInject';
        this.s3 = new this.AWS.S3();
        this.selectedTheme = '';
        this.currentThemeId = '';
        this.currentS3ThemeOption = {};
        this.currentS3ThemeOptionToUpload = {};
        this.currentThemeImageUrl = '';
      }
      getThemeDetails(theme) {
        // Code for getting and updating theme details
     }
}

When I select the option from the dropdown, it retrieves and stores the data into currentSeThemeOption. https://i.sstatic.net/88vFi.png

Despite logging the value in the console, https://i.sstatic.net/GgxGG.png

I suspect that there might be a problem with 'this' and obj in the code.

Following suggestions, I also tried adding $scope.apply() function, but unfortunately, it didn't resolve the issue.

Answer №1

Make sure to update your model within a scope.$apply() function:

fetchThemeData(theme) {
  this.$log.log(`fetching theme details for:`, theme);
  const self = this;
  
  for(let item of this.themePacks) {
    if (theme === item.title) {
      this.currentThemeId = item.themeId;
    }
  }

  this.s3.getObject({
    Bucket: `improd-image-pipeline`,
    Key: `remoteUX/qa/${self.currentThemeId}.json`,
  }, (error, data) => {
    scope.$apply(() => {
      if (error) {
        self.$log.log(error);
      } else {
        self.currentS3ThemeOption = JSON.parse(data.Body);
        self.currentS3ThemeOptionToUpload = self.currentS3ThemeOption;

        for (const property in self.currentS3ThemeOption.colors) {
          self[property] = self.getColors(self.currentS3ThemeOption.colors[property]);
        }

        self.currentThemeImageUrl = self.currentS3ThemeOption.layout.titleImageUrl;
        
        self.$log.log(`Theme option has been updated successfully:`, self.currentS3ThemeOption, self.currentThemeImageUrl);
      }
    });
  });

  this.$log.log(self.currentS3ThemeOption, this.currentS3ThemeOption);
}

Answer №2

After setting a $scope object to the ng-model, simply include

$scope.$apply();

to ensure proper binding with UI elements.

Answer №3

The issue lies within the digest cycle as it is only triggered under four specific conditions:

1. Events (such as clicks), 2. HTTP requests, 3. Changes in input fields, 4. Timers with callbacks (e.g. $timeout).

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

Use the protractor to navigate both upwards and downwards

Issue: Timeout occurred after 3005ms I implemented window.scrollTo(0,200) to scroll down the webpage. Below is the code snippet: browser.wait(function() { browser.executeScript('window.scrollTo(0,200);').then(function () { } ...

Utilizing various camera set-ups within Three.js

How can I smoothly switch between two different cameras in Three.js while transitioning from one to the other? Imagine a scene with a rock and a tree, each having its own dedicated camera setup. I'm looking for a way to seamlessly transition between ...

Choose the option in real-time with Jquery

I'm currently developing a dynamic HTML for Select Option as seen below: item += "<td class='ddl' style='width:40%;'>"; item += "<select>" item += " <option id='list' name='selector' value=" + se ...

Tips for passing the element ID as an argument in the jQuery upvote plugin function

var updateVote = function(data) { $.ajax({ url: '/vote/', type: 'post', data: { id: data.id, up: data.upvoted, down: data.downvoted, ...

Using Java script to parse and interpret a JSON file

I have a JSON file that follows this structure. Being new to JavaScript, I am looking for guidance on how to extract each key and its associated value. Can someone help me understand where to begin? AuthServer.Web": { "stuff": { "evenmore st ...

"Utilizing JSON.parse() to convert a string captured from a PythonShell back

Using PythonShell in Node to execute a Python script that generates a Python dict, such as: { "playedStatus": game['playedStatus'].encode('ascii'), "awayTeamAbb": game['awayTeamAbb'].encode('ascii'), "homeTeamAbb": ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

I am currently facing an issue with retrieving the class value that is being generated by PHP code

I am currently facing an issue with jQuery and PHP. Whenever I attempt to target the click event on the class ".id_annonce" in the dynamically generated PHP code, it doesn't retrieve the exact value of what I clicked. Instead, it always gives me a fi ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Unexpected fragments returned by Woocommerce during woocommerce_add_to_cart_fragments hook

I'm currently working on a unique customization for my WooCommerce cart where I am trying to update the quantity of a cart item dynamically. Although the updating functionality works correctly, I'm facing an issue where the cart doesn't refr ...

Exploring the realm of variable scope in JavaScript and Vue.JS

I am a newcomer to JavaScript and I have encountered an issue with the scope of my object/variable. Can you please help me understand why my {endtoken:this.token} is empty, while console.log({rawToken:e.data}) is not? I find the concept of variable scope ...

What changes can I make to my method in order to utilize async/await?

Within my React application, I have implemented a post request to the server using axios: onSubmit = async (results) => { try { const response = await axios.post("http://localhost:8080/simulate/", results); this.setState({results: ...

Angular single-time binding without the need for continuous watching

I'm currently facing a challenge with Angular's one-time binding feature. For instance, when I want to utilize ngIf with one-time binding, it typically looks like this: <div ng-if="::showImage"> <img src="somesource" img-preloader/ ...

Is it possible to incorporate both Matter and Arcade physics into the Player object?

I attempted to instantiate a player object export default class Player extends Phaser.Physics.Matter.Sprite { constructor(data) { let { scene, x, y, texture, frame } = data; super(scene.matter.world, x, y, texture, frame); this. ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Mandatory press for a function known as a click

After dealing with a previous question on this matter, I have encountered yet another issue. My goal is to rotate an element clockwise by 22 degrees and then back to its initial state of 0 degrees on click. The first function executes correctly, but the ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...

Create interactive highcharts graphs using data from a CSV file generated through PHP

I'm having trouble working with Highcharts and csv data. Take a look at this example: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/line-ajax/ $.getJSON('http://www.highcharts.com/ ...

What steps should I take to set up search paths for node modules in Code Runner within Visual Studio Code?

Just recently, I embarked on a Javascript course and successfully configured my Visual Studio Code to run JavaScript. Check out the code snippet that I came up with: const prompt = require('prompt-sync')(); var fname = prompt("First name please : ...

Using jQuery to update the input value when the mouse hovers over a div

Attempting to update an input value using jQuery mouseover. Situation: There are 5 divs with different colors and usernames. When hovering over a div, the input text (and background color for the color input) changes based on database values. Each time a ...