Modify the scoped variable using Angular's $resource module

I am facing an issue with my Angular application where I cannot get the results of a second $resource call to update a scoped variable. Initially, I am able to generate the initial view from an Angular $resource call to an external API and display the data. However, when I have a form that runs a function on ng-click which queries the API again, the scoped variable does not update with the new data.

Here is the code snippet from my controller for the initial call:


// Initial weather and geolocation data
    var Weather = $resource('http://example.com/:method');
    Weather.get({method: 'current'}).$promise.then(function(weather) {
      // Success
      $scope.weather = weather.weather;
      $scope.geolocation = weather.location;
    }, function(error) {
      // Failure
      $scope.weather = error;
    });

The initial call works fine and I can display the JSON data in the view using {{ weather.currently.temp }} as well as the data in the {{ geolocation }} variable.

However, when I try to make another request to the API upon form submission, the scoped variable does not update:


// Search functionality
    $scope.weatherLookup = function(query) {
      $http.get('http://example.com/location/' + query).then(function (value) {
        $scope.weather = value;
      });
    };

Even though the API returns valid JSON data in the value, the $scope.weather variable does not update in the view when calling $scope.weatherLookup.

I need help figuring out how to assign the value returned by the API to the $scope.weather inside the $scope.weatherLookup function so that it updates the value and reflects in the view.

Answer №1

This is my solution to the problem at hand, but I am open to hearing about other alternative or more efficient methods.

I discovered that $scope.weather was referencing multiple values due to the nature of promises returned by the $resource and $http methods. This led to $scope.weather pointing to two separate objects in the view and controller. To address this issue, I utilized $rootScope to ensure consistency with the weather object being overwritten consistently.

Below is the updated code snippet:

'use strict';

angular.module('myApp')
  .controller('WeatherCtrl', function ($scope, Restangular, $rootScope) {

    // Fetch initial weather data (WITH $rootScope)
    Restangular.one('current').get().then(function(weather) {
      $rootScope.weather = weather.weather;
      $scope.geolocation = weather.location;
    });

    // Implement search functionality
    $scope.weatherLookup = function(query) {
      Restangular.one('location/' + query).get().then(function(newWeather) {
        $rootScope.weather = newWeather;
        console.log($rootScope.weather);
      });
      console.log($rootScope.weather);
    };

  });

I made a switch from Angular's native services such as $resource and $http to adopt the powerful Restangular library. However, even after this transition, the original issue persisted until I incorporated the use of $rootScope. Through testing with both $resource and $http, it became evident that the problem stemmed from $scope.weather splitting off and referencing distinct objects because of how $scope and promises operate in Angular.

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

The integration of Google Translate with Javascript on HtmlEditorExtender is experiencing difficulties and is not functioning properly

I implemented the use of a text box with ajaxtoolkit HtmlEditorExtender (Rich textbox) to translate English to Gujarati using Google translation Javascript. The translation function works perfectly with the regular text box, but encounters issues when used ...

Confirming the structure of a URL using JavaScript/jQuery

I have a text field where users input URLs. I need to validate the format of the URL using regular expressions. Specifically, I am looking for invalid URLs such as: http://www.google.com//test/index.html //Invalid due to double slash after hostname http: ...

Displaying markers and coordinates in the center circle of a Google Map using Vue.js

Is there a way to display the markers that fall within the specified radius on my map? I need to showcase these locations based on their proximity to a central point, as this will be essential for developing a function that identifies places within a certa ...

Is my directive not displaying the desired content on the HTML page?

I'm facing an issue with a custom directive in AngularJS that is supposed to draw a circle using SVG. However, upon loading the page, the circle doesn't appear, and even the text within the template is not showing up. What could be causing this ...

Step-by-Step Guide on Dividing Table Row Data into Two Distinct Tables

At present, I have created a dynamic table that retrieves data from the database using forms in Django. I'm facing an issue with this table as even though there are 7 columns, only 2 of them are visible. However, all 5 hidden columns do contain impor ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

"Assertj is used to compare the extracted values, specifically when they are arrays

My situation involves requesting sets of names from two different systems and checking if they are equal, regardless of the order. The code below seems to work fine: assertThat(asList(assertThat(firstJSON) .flatExtracting("innerObject") .extractin ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...

Using Node.js for a game loop provides a more accurate alternative to setInterval

In my current setup, I have a multiplayer game that utilizes sockets for asynchronous data transfer. The game features a game loop that should tick every 500ms to handle player updates such as position and appearance. var self = this; this.gameLoop = se ...

Output certain values in a Python dataframe based on the lambda function applied

I am currently working on a piece of code that involves reading a json file and using a lambda function to remove certain values. Here is the code snippet: import pandas as pd data = pd.read_json('filename.json',dtype='int64') data = da ...

Renewed Promises: Exploring Promises in Angular JS

Revised with HTTP and initial code inspired by requests/Refer to the end of the post: Lately, I have been seeking help from the amazing SO community as I navigate through my AngularJS learning journey. I used to be a traditional C programmer but recently ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

Can you explain the significance of 1x, 3x, etc in the Karma code coverage report for Angular unit testing?

I am a beginner when it comes to Unit Testing in Angular. Recently, I set up karma with code coverage using angular-cli. After running the command ng-test, I checked out the code coverage report and noticed references like 1x, 3x, etc. next to my code line ...

What is the solution for halting code execution in a foreach loop with nested callbacks?

Currently, I am in the process of setting up a nodejs database where I need to retrieve user information if the user exists. The issue I'm facing is that when I return callback(null) or callback(userdata), it does not stop the code execution and resul ...

I'm having issues with my pop method - it doesn't seem

Hello everyone, I am new to core JavaScript and currently learning how to create an array. I have written the following code but for some reason, the pop method is not working as expected. var players=['david','micky','Ryan' ...

Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color. Here's my code: color-variatio ...

Distinctive titles for JavaScript constructors/prototypes compared to classes

When working with JavaScript ES6, classes allow us to write code like this: class RectangularShape { constructor(height, width) { this.height = height; this.width = width; } getArea() { return this.height * this.width } static some ...

The error message encountered in Python is: "Cannot iterate over the '_csv.writer' object due to a TypeError."

I'm currently facing an error while parsing json to csv: for i in data: TypeError: '_csv.writer' object is not iterable Here is the code snippet: import json import csv with open("Data.json", 'r') as file: data = json.load( ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

Can you provide instructions on how to replace the icon within the TablePagination element in MUI?

I'm currently working on a React project where I've implemented the MUI component known as TablePagination This TablePagination component is situated within the Table component, just like in the image provided below. https://i.stack.imgur.com/B ...