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

Creating a function in React to be passed as a prop

Recently, I was given the task of enhancing a user interface as a small challenge to help me dive into the world of programming. My goal is to incorporate a date picker into my search bar to allow users to filter their search results by selecting specific ...

The compilation of the module has encountered an error with the PostCSS loader. There is a SyntaxError at line 2, character 14 indicating an unknown

I am developing an Angular 8 application. Currently, I am incorporating AlertifyJs into my project. In the styles.css file of Angular, I have imported these libraries: @import '../node_modules/alertifyjs/build/alertify.min.js'; @import '. ...

How to convert jQuery data into JSON format

I am dealing with data in the following format: ID=300573&CarNo=1&Account=AAAA&AccountingDate=3%2F21%2F2013&Description=NewCar&CheckAmount=666666&ClearedAmount=-3446.5&ClearedDate=4%2F9%2F2013&Sent=S&SentDate=4%2F4%2F20 ...

Why is Handlebars {{body}} not rendering my HTML tags properly?

I am perplexed by the fact that the example in the other file is not showing. While working on a CRUD project with Mongo, Express, and Node, I encountered an issue. The code wasn't functioning as expected, so I paused to figure out why. <!DOCTYPE ...

Improving Zen Coding to integrate with JavaScript files on Sublime Text2

Sublime Text2 is hands down my go-to editor, except for one minor hiccup - the Zen Coding plugin only works with CSS and HTML files. There are plenty of times where I'd love to use Zen Coding with JavaScript or other file types, like incorporating HTM ...

Automatic logoff will occur after 15 minutes of inactivity in C# programming language

After a period of 15 minutes, the following method logs out the user. However, it currently logs out the user even if they are active. I am seeking a solution where the method will only log out the user if they have been inactive for the full 15 minutes. ...

What could be causing the sluggishness of this ajax call?

After implementing an ajax function on the page load event, I noticed that there was no record of the call in the server log (which logs all entrance and exit points of all MVC server methods). The request from the JavaScript to the server was taking an un ...

Deleting a string by utilizing the Ternary operator in JavaScript

How do I remove the [object Object] from my output shown in the console? I'm looking to print the output without the [Object Object]. Is it possible to achieve this using a ternary operation? data:[object Object] text:Data is supplied by Government ...

Is there a way for me to position my arrow beside the header while still keeping the toggle function intact?

Can anyone assist me in positioning my arrow next to the header text, which I toggle on click? I attempted placing the arrow <div> into the H1 tag, but then the toggle function stops working. Any help would be greatly appreciated! Please includ ...

POWER QUERY - Data in a JSON request with incorrect structure

I have encountered an error while developing a request in Power BI's Power Query. The error message is as follows: Invalid format payload in a JSON request. Here is the code snippet: let URL1 = "example/login", POST = [ #"Conten ...

The phonegap page redirection is failing, as the 'location' property of the object does not function correctly

I'm attempting to implement a straightforward page redirection in PhoneGap using JavaScript. Within an iframe, I have the following code: window.parent.location("event_select.html"); Unfortunately, this approach is unsuccessful and results in the fo ...

I am experiencing an issue where the ng-message is not appearing during validation

While developing a form in AngularJS, I encountered an issue with the required attribute not working for the username field upon form submission. <div ng-app="myOwnModule" ng-controller="myOwnCon"> <form name="myOwnForm" novalidate > < ...

Challenges with using the $filter('limitTo') function in AngularJS

Struggling with implementing the limitTo filter in JavaScript The angularjs docs for limitTo explain that the filter should be used as follows: $filter('limitTo')(input, limit, begin) It's important to note that the begin parameter is opt ...

Material Ui and react-router onClick event latency on handheld devices

My React application is currently using @material-ui/core v.1.2.1 and react-router 3.0.2, which I am unable to update at the moment. Whenever I click a button that handles navigation, there is a noticeable delay of around 2 seconds before it works. In ord ...

Exploring the concept of utilizing named arguments within Express.js routing

I've searched extensively, but can't seem to find any information on this topic. My goal is to create requests like the following: url/list/message=hello?id=1234 Despite my efforts, I have not come across any resources on how to achieve this us ...

Using `ng-class` strategically within a list of elements

Currently, I am working with a list of checkboxes and trying to apply a class conditionally using ng-class when the checkbox is clicked. However, the issue I am facing is that the class gets applied to all items in the list instead of just the specific one ...

The node application route appears to be malfunctioning

Recently delving into the world of node JS, I encountered an issue while working on my application with the following 3 files. http.createServer(app).listen(**app.get('port')**, function(){ The error message reads 'undefined is not a func ...

How to ensure an object is consistently rendered above all others using Three.js

Currently working on adding a dynamic command arrow that follows the cursor on the display. However, I have encountered an issue where it gets obscured by other elements on the screen. Is there a method to adjust the z-buffer or implement a workaround to ...

Displaying the information fetched using axios on the screen using node.js

Is there a way to display the information from the input boxes in the image on the screen using node js? ...

Utilizing ngRepeat within a custom directive's template

Check out this plunker to see my current progress. angular.module('app', function(){ }) .run(function($rootScope){ $rootScope.values = [1,2,3,4]; }) .directive('outer', function(){ return { restrict:'E', scope:{ ...