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

JavaScript enables users to store over 5 megabytes of data on their client devices

Is there a way to store more than 5mb in the client browser? I need this functionality across various browsers including Firefox, Chrome, Internet Explorer, Safari (iOS), and Windows Phone 8 Browser. Initially, localStorage seemed like a viable option as i ...

What is the best way to target the iframe within the wysihtml5 editor?

Currently, I am utilizing the wysiwyg editor called wysihtml5 along with the bootstrap-wysihtml5 extension. As part of my project, I am designing a character counter functionality that will showcase a red border around the editor area once a specific maxl ...

Update the JavaScript to modify the styling based on the specific value of the

Is there a way to apply specific style properties to images only if they already have another property? I've managed to achieve this with the following code snippet: if ($('#content p img').css('float') == 'right') $ ...

"The functionality of the express post method does not seem to be working properly when accessing

I am having trouble retrieving form data sent using the "POST" method from an HTML form in my app.post method. I am unable to access anything from req.body. Can anyone point out what mistake I might be making? Here is my HTML form - <form method=" ...

"Troubleshooting: Why are the Button Styles in Ionic 4 CDN and VueJS not Applying

Greetings! I am currently incorporating the Ionic 4 CDN into my VueJS application. Everything seems to be working smoothly, except for the Buttons. <button ion-button>Button</button Here is how I am adding the CDN as per the official documentati ...

Steps for invoking the controller method in the routeProvider resolve function

I would like to update the data and then display the view associated with this controller. Here is the code snippet: angular.module('myApp.student', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { ...

What could be causing my jQuery to fail when the page first loads?

My script only seems to work when the input changes, but I want it to start working as soon as the page loads and then continue to update when the input changes. Can anyone help me figure out what's wrong with my script? <script src="http://co ...

Fetching an image from Firebase Storage for integration into a Vue application

I am encountering an issue while trying to fetch an image from my firebase storage to display it in my Vue application. The upload process from the app to firebase storage runs smoothly, but there is an error during retrieval. My setup involves using the F ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Enhancing TypeScript Data Objects

I'm looking to expand a data object in TypeScript by introducing new fields. Although I know it's a common practice in JavaScript, I'm struggling to get it to compile without making bar optional in the provided snippet. I am interested in f ...

Distribution of data in K6 according to percentage

Is it possible to distribute data based on percentages in K6? For instance, can you demonstrate how to do this using a .csv file? ...

Tips for sorting through an array of items in AngularJS

In my question dataset model, the structure looks like this: { "id": 5, "description": "Is Facebook integration available on your site?", "question_category_id": 3 } Additionally, here is the question_category structure: { "id": 1, ...

Calculate the sum of values in a JSON array response

I recently received a JSON string as part of an API response, and it has the following structure: { "legend_size": 1, "data": { "series": [ "2013-05-01", "2013-05-02" ], "values": { "Sign Up": { "2013-05-05": 10, ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

RSS feed showing null xml data with jQuery

Working on coding a straightforward RSS feed utilizing jquery and pulling data from Wired. Everything appears to be functioning correctly, except for one issue - after the description, an unknown value of NaN is appearing in the result. It seems to be comi ...

Tips for customizing the IconButton appearance in material-ui

While Material-ui offers a default icon button, I am interested in customizing its design to resemble this: IconButton design needed Could you please advise me on how to make this change? Thank you. ...

Troubleshooting minified JavaScript in live environment

Trying to wrap my head around AngularJS and Grunt. In my GruntFile.js, I have set up two grunt tasks for development and production. In production, I am using uglification to combine multiple js files into one. I am in need of some advice or tips on how t ...

Android browser experiences a sudden surge of unexpected data influx

I am facing an issue with my application where it maps an array from the state. The array should ideally only contain 6 sets of data, as limited by the backend. However, sometimes it spikes and displays data that is not supposed to be there or shows old da ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

Is it possible to utilize rspec for conducting feature testing on an integrated rails-angular application?

My Rails-Angular application is very basic and integrated. It simply renders a link, fetching data from a GET request to Rails: 'use strict'; angular.module('angularRspec.controllers') .controller('FightersController', ...