The UI does not reflect changes to the scope variable after it is updated by a service call

When I add a new item to the scope from another service, the select tag options that come from the service do not reflect the newly inserted value immediately. The new option only appears after refreshing the page. It seems like the scope is not updating the results when its values change. Here is the code I am using:

HTML code:

<select ng-model="holidaySelected"
    ng-options="opt as opt.holidayName for opt in list_of_holidaytypes">
</select>

JS code:

$http({
    method : 'get',
    url : 'url'//url is here
}).then(function(response) {
    $scope.list_of_holidaytypes = response.data;
});

After calling another service and then calling this service again, the new option is not showing up in the UI.

Answer №1

Everything looks great in the code. However, I have a suspicion about the API response. Could you please let me know the exact response you are receiving from the API? It should look something like this:

$scope.list_of_holidaytypes = [{holidayName:'Name1' }, {holidayName:'Name2' }];

Answer №2

It appears that the code $scope.list_of_holidaytypes = response.data; is being executed in the service, but according to Angular documentation, $scope cannot be accessed inside a service.

My recommendation is to move the code responsible for populating $scope.list_of_holidaytypes to the controller.

Here is an example:

Controller Code:

function MyCntrl($scope, MyService) {
  function successCallback(response) {
     $scope.list_of_holidaytypes = response.data;
  }

  function failureCallback(response) {
    $scope.list_of_holidaytypes = null;
  }

  $scope.fetchList = function() {
     MyService.fetchList(successCallback, failureCallback); 
  }
}

Service Code:

function Myservice($http) {
  this.fetchList = function(successCallback, failureCallback) {
    $http({
      method : 'get',
      url : 'url'//url is here 
    }).then(function(response) {
      successCallback(response);
    }, function(response) {
      failureCallback(response);
    });  
  }
}

This approach should work without any issues.

Answer №3

I have discovered the solution. In order to update the scope variable in the UI, I am utilizing a service to retrieve the most up-to-date value of the scope variable within the service. Below is the code snippet:

Code for updating initial state:

    $scope.OnloadServiceData = function(){
           $http({
           method : 'get',
           url : 'url'//url is here
           }).then(function(response) {
           $scope.list_of_holidaytypes = response.data;
    });
};
$scope.OnloadServiceData();

Code in another controller:

 $http({
    method : 'post',
    url : 'url'//this is another service
}).then(function(response) {
    $scope.xyz= response.data;
    $scope.OnloadServiceData();//calling the service to fetch result in UI
});

Answer №4

give this a shot

try this first

let me show you how it's done

once the user calls

 vm.yourevent;

implement it now

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

Several challenges with managing date filters and formats in jqgrid

I am facing several challenges with a single column in jqGrid that is meant to handle date information: 1- The date is retrieved from the back-end and displayed as 29/03/2017 00:00:00. When I attempt to format it using formatter: "date", formatoptions: { ...

What is the best approach to establish multiple global prefixes in a NestJS project?

I am looking to define multiple Global Prefixes for my application such as: admin/products admin/users admin/... api/products api/search api/... shop/products shop/cart shop/... In the main.ts file, I can set a single global prefix using th ...

Field cannot be submitted without the required input after an Ajax request

I want to ensure that all my text/email input forms require a submission before you can "Submit" the email. Unfortunately, when using Ajax to prevent the page from refreshing after pressing the button, the required attribute does not function properly. T ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

Monitor modifications to a DOM element's ClientRect dimensions

I have developed a component that utilizes the context feature to register a DOM node and include it in a QuadTree. export default class SelectableGroup extends React.PureComponent { getChildContext() { return { register: this.register, ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Resolving the Smooth Scrolling Problem

Here is a simplified version of what I am currently working on: Although I have managed to get the scrolling functionality to work, there seems to be an issue with transitioning from one section to another. For example, when clicking on NUMBER 3, it s ...

Interact with various contenteditable sections by navigating with the arrow keys

I have a challenge with multiple <p contenteditable="true"></p> elements on my page. I am seeking a solution to enable the use of arrow keys to navigate seamlessly across these separate elements as if they were one cohesive editable element. F ...

What is the correct way to incorporate Regular Expressions in Selenium IDE coding?

Using regular expressions to check for a correct answer from a prompt has been challenging. The current expression seems to be giving unexpected results, marking valid answers as false. For instance, when inputting the number 3, Selenium indicates that the ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Breaking apart a string that consists of boolean values

Presented below is a JavaScript function function cmd_parse( cmd ) { return cmd.split( /\s+/ ); } For instance, when calling the function like this words = cmd_parse("hello jay true"); The output would be words[0]="hello" words[1]="jay" wor ...

When running through Selenium web driver, JS produces inaccurate results

Currently, I am utilizing JavaScript to determine the number of classes of a specific type. However, when I run the JS code in Webdriver, it provides me with an incorrect value. Surprisingly, when I execute the same JavaScript on the Firebug console, it gi ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

Improving callback functions in Express/NodeJs for a more pleasant coding experience

function DatabaseConnect(req, res) {...} function CreateNewUser(req, res) {...} function ExecuteFunctions (app, req, res) { // If it's a POST request to this URL, run this function var firstFunction = app.post('/admin/svc/DB', func ...

Leveraging a handful of $guardians to $transmit

Here is the markup I am working with: <div class="grandparent"> <div class="parent" ng-repeat="parent in parents"> <div class="child" ng-repeat="child in parent.children"> <div class="grandchild" ng-repeat="gra ...

"Prevent users from taking screenshots by disabling the print screen key

Can someone help me figure out how to prevent users from taking a screenshot of my website by disabling the print screen key? Here's the code I've tried so far: <SCRIPT type="text/javascript"> focusInput = function() { document.focus() ...

Issues regarding innerHTML

I have a collapsed table with a link that collapses its content. My goal is to change the link (such as from "+" to "-" and vice versa) using JavaScript. I was able to achieve this, but now my table no longer collapses. Here is the code snippet: <div c ...

Is it possible to eliminate the dedupe feature in npm?

By mistake, I accidentally ran the command npm dedupe and now all of my node_modules directories are flattened. While this reduces file size, it's making it more difficult to find things. Is there a way to reverse this and return to the hierarchical f ...

Using Ajax with Controller Action in Yii2

As a newcomer to programming, I am facing an issue where I need to call a function when the user inputs data and clicks the submit button. Although I am working with Yii2, I lack experience in Ajax. Despite my efforts, the controller action is not being tr ...

(node:9263) UnhandledPromiseRejectionWarning: ValidationError: ideas validation failed: Missing required field imageUrl

Encountering the UnhandledPromiseRejectionWarning: ValidationError validation failed: imageUrl: PathimageUrlis required error when attempting to upload an image. However, removing or commenting out the required: true keyword in the model file for imageUrl ...