Updating data scope in AngularJS using $http request not functioning properly

I am facing an issue where the $scope.user_free_status is not updating when I set a user free, but works perfectly fine when I unset the parameter. It's strange that I need to reload the page in one case and not the other. The data fetched is stored in local storage.

Below is the code snippet:

    .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html",
    controller: 'InitialCtrl',
    resolve: {
      theUserFreeStatus: function(DataService) {
        return DataService.getUserFreeStatus();
      }
    }
  })

Controller:

.controller('InitialCtrl', function($scope, $state, DataService ,FreeService, SharedService, theUserFreeStatus) {
// Showing set free but not unset or not
  if (FreeService.isSetFree()) {
    $scope.showSetFree    = false;
    $scope.showUnSetFree  = true;
  } else {
    $scope.showSetFree    = true;
    $scope.showUnSetFree  = true;
  }

  // Show the Free status set when arriving on page/app
  $scope.user_free_status = theUserFreeStatus;
  // Set user as Free
  $scope.setFree = function(activity, tags) {
    FreeService.setFree(activity, tags).success(function() {
      console.log($scope.user_free_status);
      $scope.user_free_status = DataService.getUserFreeStatus();
      console.log($scope.user_free_status);
      $scope.showSetFree    = false;
      $scope.showUnSetFree  = true;
      SharedService.goHome();
    })
  }  

  //// Free status unset
  $scope.unsetFree = function() {
    FreeService.unsetFree().success(function() {
      $scope.user_free_status = [];
      $scope.showSetFree    = true;
      $scope.showUnSetFree  = false;
      SharedService.goHome();
    });
  };
})

The services:

.factory('FreeService', function(WebService, $localstorage, $ionicPopup, DataService, $sanitize, CSRF_TOKEN) {
    var cacheFreeStatus = function(free_status) {
        $localstorage.setObject('user_free_status', free_status)
    };
    var uncacheFreeStatus = function() {
        $localstorage.unset('user_free_status')
    }
    return {
        setFree: function(activity, tags) {
            var status  = { SOME STUFF BLABLABLA };
            var setFree = WebService.post('setstatus/', sanitizeStatus(status));
            setFree.success(function(response) {
                console.log('available' + response.flash);
                cacheFreeStatus(response.status_response);
            })
            setFree.error(freeError)
            return setFree;
        },
        unsetFree: function() {
            var details  = {OTHER STUFF};
            var unsetFree = WebService.post('unsetstatus/', details);
            unsetFree.success(function(response) {
                console.log('unset ' + response.flash);
                uncacheFreeStatus(response.status_response);
            })
            unsetFree.error(freeError)
            return unsetFree;

        },
        isSetFree: function() {
            return $localstorage.get('user_free_status');
        }
    }
})
.service('DataService', function($q, $localstorage) {
  return {
    activities: $localstorage.getObject('activities'),
    getActivities: function() {
        return this.activities;
    },
    user_free_status: $localstorage.getObject('user_free_status'),
    getUserFreeStatus: function() {
        return this.user_free_status;
    }
  }
})
 * Local Storage Service
 ------------------------------------------------------*/
.factory('$localstorage', ['$window', function($window) {
  return {
    set: function(key, value) {
      $window.localStorage[key] = value;
    },
    unset: function(key) {
      localStorage.removeItem(key);
    },
    get: function(key, defaultValue) {
      return $window.localStorage[key] || defaultValue;
    },
    setObject: function(key, value) {
      $window.localStorage[key] = JSON.stringify(value);
    },
    getObject: function(key) {
      return JSON.parse($window.localStorage[key] || '{}');
    }
  }
}])

After setting the user's status, the console shows that the $http call was successful, but the $scope variable remains an empty array until I reload the page. However, when unsetting the user's status, the $scope updates without needing a page reload. The Webservice functions simply make the $http call.

Any thoughts on how to ensure that the $scope.user_free_status updates correctly without requiring a page reload?

Appreciate your assistance!

Answer №1

The data service you provided is being injected as a service, however you have not attached the functions to it properly. Instead, you have returned it as part of a literal, similar to how you would do in a factory function.

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

Error encountered in Intellij for Typescript interface: SyntaxError - Unexpected identifier

I am currently testing a basic interface with the following code: interface TestInterface { id: number; text: string; } const testInterfaceImplementation: TestInterface = { id: 1, text: 'sample text' }; console.log(testInterface ...

Find the object in an array that has the most recent date property

Suppose I have an array of objects like this : let sampleArray = [ { "id": 5, "date": "2016-01-15T16:18:44.258843Z", "status": "NEW", "created_at": "2016-01-29T13:30:39.315000Z", "updated_at": "2016-01-29T13:30:39.315000Z", "requ ...

I am experiencing issues with staying logged in while using Passport and sessions. The function "isAuthenticated()" from Passport continuously returns false, causing me to not remain logged in

I have been working on implementing authentication with Angular, Passport, and sessions. I can successfully create a new user and log in, but I am facing an issue: Problem Every time I check if the user is authenticated using Passport's isAuthentica ...

Executing a controller method in AngularJS when redirecting a page

I am currently working on an app using Cordova/Phonegap, Ionic, and AngularJS. One challenge I am facing is trying to call a method from a controller inside my app when redirecting to another HTML page (secondPage.html). This particular method (secondMetho ...

jQuery form validation issue, unresponsive behavior

<!DOCTYPE html> <html> <head> <title> jquery validation </title> </head> <body> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js" type="text/javascript"> ...

AngularJS: Patience for an asynchronous request

I'm having trouble understanding the concept of promises in AngularJS. Here is a provider I have: var packingProvider = angular.module('packingProvider',[]); packingProvider.provider('packingProvider',function(){ ...

Struggling to constrain a TextField component from material-ui and encountering an issue with the inputRef

Currently, I am attempting to restrict the length of an autocomplete textfield within my project. However, when I apply InputProps={{ maxLength: 2 }}, it throws an error stating that my inputRef.current is null. Even though I have set the ref in the inputR ...

Which is more efficient: Implementing caching on the frontend or on the

Currently, I am using ajax to send requests to the backend server, where operations are performed and responses are received: function getData() { new Ajax().getResponse() .then(function (response) { // handle response }) .catch(functi ...

Error: Identical div IDs detected

<div id="tagTree1" class="span-6 border" style='width:280px;height:400px;overflow:auto;float:left;margin:10px; '> <a class="tabheader" style="font-size:large">Data Type</a><br /> <div class="pane">Refine sea ...

AngularJS end-to-end testing using Testacular causes browser disconnections for all tests

I'm currently working on setting up e2e tests for my AngularJs project using testacular. I've successfully launched a node.js-based web server and can see the files being sent when a URL is loaded. I am also able to view the expected results in m ...

Just beginning my journey with coding and came across this error message: "Encountered Uncaught TypeError: Cannot read property 'value' of null"

As a newcomer to the world of coding, I am excited about working on a side project that allows me to practice what I am learning in my courses. My project so far is a temperature calculator that incorporates basic HTML and JS concepts. My goal is to improv ...

Despite encountering an error in my terminal, my web application is still functioning properly

My code for the page is showing an error, particularly on the home route where I attempted to link another compose page The error message reads as follows: Server started on port 3000 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after t at new Node ...

What is the best way to track and document the specific Context Provider being utilized while invoking useContext?

After creating a custom component that displays AuthContext.Provider with specific values, I encountered an issue. Even though it functions correctly, when I utilize useContext within a child of the AuthProvider component, my code editor (VS Code) is unabl ...

The data in Next.js getStaticProps does not update or refresh as expected

As I recently transitioned to working with Next.js, I have encountered several challenges. One issue that arose was related to the use of useEffect in React compared to its behavior in Next.js. In my index file, I have implemented the following code: impo ...

"Exploring the world of mocking module functions in Jest

I have been working on making assertions with jest mocked functions, and here is the code I am using: const mockSaveProduct = jest.fn((product) => { //some logic return }); jest.mock('./db', () => ({ saveProduct: mockSaveProduct })); ...

Interactive image popups with JavaScript

Seeking assistance in generating a popup when selecting an area on an image map using Javascript. As a novice in JS, I have successfully implemented popups for buttons before but encountered issues with this code within the image map - the popup appears br ...

Implementing phone verification code delivery using ReactJS and Twilio client: Step-by-step guide

I've been scouring the internet for the past 8 hours and haven't been able to find a tutorial on using Twilio to send SMS messages with ReactJS. Does anyone know of a good tutorial for this? ...

Share the Nav tag value or name during an OnClick event within ReactJS

I've been facing a minor issue that I just can't seem to figure out - how do I pass a value to my OnClick event? It's crucial for me to pass this value as it corresponds to the options in my menu and is essential for some processes: This is ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Creating an array of objects in Javascript by setting two different values as a range

Given an array of objects structured as follows: [{value: "a", start: 1950, end: 1954, description: "aaa"}, {value: "b", start: 1953, end: 1956, description: "bbb"}, {value: "c", start: 1960, end: 1962, des ...