Monitor $localStorage for any modifications

Utilizing the ngStorage module, which can be accessed at this link: https://github.com/gsklee/ngStorage

In order to maintain a lastSeenId for a real-time social feed in my hybrid app (Laravel/AngularJS), I am storing it in localStorage instead of $scope.

Within my StatusesController, upon receiving an array of data (or nothing if no updates), I extract the last item from the array and set my $localStorage variable like so:

$localStorage.lastStatusSeen = lastId;

In my navigation controller, I set new counters for users to track any missed content. To retrieve the lastSeenId, I use: $scope.$storage.lastStatusSeen, which is then sent to the API to fetch the number of unseen status posts.

This system functions smoothly as the user navigates through the status page, updating the local storage variable with the latest ID when new data is available.

The problem arises with my NavigationController not detecting these changes, consistently passing the initial lastSeenId from the user's first visit to the page.

Is there a method to monitor changes to that key in local storage?

EDIT: Revised code snippet as requested

    app.controllers.navigationController = ['$scope', 'pollingService', '$localStorage', function($scope, pollingService, $localStorage) {

    $scope.lastStatusSeen = $localStorage.lastStatusSeen;

    $scope.$watch(function () {
        return $localStorage.lastStatusSeen;
    }, function (newVal, oldVal) {
        if (!newVal) {
            return;
        }

        if (newVal !== oldVal) {
            // Assign to a locally scoped variable or any other action here...
            $scope.lastStatusSeen = newVal;
            // Consider invoking a method to handle logic outside of this function
            //$scope.onIdChange(newVal, oldVal); // Include oldVal if needed
        }
    });

    pollingService.startPolling('emailCount', 'api/email/new-count', 5000, function(response) {
        $scope.emailCount = response.data;
    });

    pollingService.startPolling('statusCount', 'api/social/new-count?lastid=' + $scope.lastStatusSeen, 5000, function(response) {
        $scope.socialCount = response.data;
    });

}];

Answer №1

To view it, utilize the $watch method of any scope entity in angular ($scope or $rootScope):

$scope.$watch(function () {
    return $localStorage.lastStatusSeen;
}, function (newVal, oldVal) {
    if (!newVal) {
       return;
    }

    if (newVal !== oldVal) {
        // Store in a local scoped variable, or perform other actions here
        // It is recommended to call a method for processing outside this code block

        $scope.onIdChange(newVal, oldVal); // Use oldVal if needed
    }
});

Take caution with performance as this executes during almost every $digest cycle. Also, you can link this watcher to a variable and cancel it whenever necessary:

var watchIdStored = $scope.$watch(function () {
    /* ... */

To remove it, invoke the variable as a function:

watchIdStored(); // Removes the $watcher

Edit 1:

The issue lies within

pollingService.startPolling('statusCount', 'api/social/new-count?lastid=' + $scope.lastStatusSeen)
. This creates a static string that does not change. Update this information when changes occur to provide the polling service with the current data.

If you place a console log inside the watcher where the variable is updated, you will see the updates taking place.

Edit 2:

Since you have a stopPolling() method, consider creating a setup/destroy function in your controller:

function _setupPolling (name, url, pollingTime, callback) {
    pollingService.stopPolling(name);

    pollingService.startPolling.apply(pollingService, arguments);
}

Now, call this function whenever changes are made to $localStorage.lastStatusSeen:

$scope.$watch(function () {
    return $localStorage.lastStatusSeen;
}, function (newVal, oldVal) {
    if (!newVal) {
        return;
    }

    if (newVal !== oldVal) {
        console.log(newVal);

        // Store in a local scoped var, or anything else
        $scope.lastStatusSeen = newVal;
        // It's recommended to call a method for processing outside this block

        _setupPolling('statusCount', 'api/social/new-count?lastid=' + $scope.lastStatusSeen, 5000, function(response) {
            $scope.socialCount = response.data;
        });
    }
});

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

Unexpected error occurs when modifying HTML5 video source using JQuery on Internet Explorer

Currently, I am working on developing a web application using asp.net, Bootstrap, and JQuery. While testing it on LocalHost, I encountered an issue that needs debugging. The navigation bar of my application has a dropdown menu with links to tutorial video ...

Does anyone know of a convenient tool that can automatically provide suggested street names for mailing addresses in every country across the globe, for free?

Is there a convenient tool that automatically completes street addresses for various countries worldwide? I'm considering options similar to YQL from Yahoo or Foursquare. I'd like to provide users with suggestions of known street names as they ...

Transferring an array to PHP using AJAX

In this coding scenario, I initialize my array: let myArray = []; Within a loop, elements are added to the array as follows: myArray.push($(this).data('id')); // Example: [1, 2, 3, 4] Subsequently, I transmit this data to PHP using AJAX throu ...

Jump straight to the top of the page with just a click using the Google Maps Store Locator

When I use my Store Locator and click on an anchor like "Zoom Here," "Directions," or "Street View," the href hash always brings me back to the top of the page. How can I prevent this from happening? I've tried examining the minified source code for t ...

Understanding the $scope array and the use of $scope.$apply in AngularJS is

I'm currently diving into the world of AngularJs and encountering an issue that needs addressing. My goal is to display an array of items within a view. Initially, in the controller, I set up the array using $scope.arrName = [], then proceed to acqui ...

Ag-Grid is failing to display MenuTabs

I need help getting the columns menu tab to appear in Ag-Grid. It should be a simple task. I want both the general and columns tabs, similar to the demo shown here Currently, when I specify both tabs, only the general tab is displayed. If I specify just t ...

"Production environment encounters issues with react helper imports, whereas development environment has no trouble with

I have a JavaScript file named "globalHelper.js" which looks like this: exports.myMethod = (data) => { // method implementation here } exports.myOtherMethod = () => { ... } and so forth... When I want to use my Helper in other files, I import it ...

How come I am receiving {"readyState":1} in the DOM instead of JSON data in AngularJS?

Currently, I am facing an issue where instead of the JSON data (which consists of only 49 items) showing up on the DOM, I am getting {"readyState":1}. I believe this is just a test to ensure that my code is functioning correctly. Although I have identifie ...

The total height of the document's body in jQuery is not equal to the sum of the viewport height and the window's scroll top position at the bottom of the document

Why does the document height appear smaller than the window scroll top value plus the viewport height when I reach the end of the document? Shouldn't they be equal? I've been struggling with this issue for hours and can't seem to figure it o ...

Performing an AJAX request from a subfolder

Can anyone help me figure out how to make an ajax request from a page located in a subdirectory and receive a response? On my webpage, index.jsp is situated within a subdirectory called /vf2. In this page, there is a script file included: <script src=" ...

Is there a way to invoke a function using a variable in place of its actual name?

Check out my code snippet: $('.click').on('click', function(){ $.ajax({ url : $(this).siblings('a').attr('href'), dataType : 'JSON', success : function (tags) { $ ...

Tips for transferring data from a parent component to a child component in React?

Recently, I've been restructuring a small application that was initially confined to one file by breaking it into its own separate components. Right now, I have a child component called UsersTable which I am displaying within the parent component User ...

What is the best way to apply a border-radius to the top of bars in @nivo/bar?

Is it possible to apply a border radius to the tops of each stack in a stacked responsive bar created from the Nivo library, without affecting the bottom? Currently, the responsive bar's border radius applies to both the top and bottom. Thank you! ...

Using StencilJs/Jsx: Displaying nested components with rendered HTMLElements

Welcome to my custom component: @Component({ tag: "my-alert-list", styleUrl: "alert-list.scss", shadow: true, }) export class AlertList { @State() alertList: object[] = []; @Method() async appendAlert( type: string, message: string, ...

Guide on syncing Bootstrap 4 sliders using a single set of controls

Is it possible to synchronize a bootstrap 4 carousel with controls to a carousel without any controls? 1) When the control arrows are clicked, both carousels will slide simultaneously. 2) Hovering over either carousel will pause both carousels from slidi ...

Is there a way to remove a particular map from Firestore?

In my Google Firebase setup, I have uniquely named each Map to serve as the index for every document. Using Vuejs (Javascript), I have structured it as follows: eQFelbD432T (Collection Name- user.uid) SKILLS (Document Name) ProjectManangement (Map Na ...

What is the best way to combine two nearly identical arrays/objects using underscorejs or a similar library?

In the realm of lists, there exists an old list and a new one. The mission at hand is to combine both, even in the presence of newly added key-value pairs. var oldList = [{ id: 1, name: 'Michael', sex: 'male', goodlooking: 1 }, ...

Subtracting Arrays Containing Duplicates

Imagine having two arrays defined like this: const A = ['Mo', 'Tu', 'We', 'Thu', 'Fr'] const B = ['Mo', 'Mo', 'Mo', 'Tu', 'Thu', 'Fr', 'Sa&ap ...

What is the best way to send HTML tag content to mark.js and delimit them with a space or comma?

I have been utilizing the mark.js library to highlight keywords on a webpage, and it's been working well. However, I now need to insert an extra space or a comma after each tag such as h1, h2, etc. Initially, I thought about using a loop like the one ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...