It seems like the data saved on an angular service is not being retained for the long term

Trying to implement ng-show for navigation by toggling div tags based on page

Successfully implemented functionality but struggling to trigger "pageChange()" from different controllers

After researching, discovered the concept of services

Now have a service storing the page variable that can be modified by other controllers

Issue is the page variable resets to its initial value and unsure how to rectify this

service:

app.service('navigationService', function() {
    var pa = this; //pa representing parent
    this.page;

    this.changePage = function(p){
        // p is the new page
        pa.page = p
        console.log(pa.page);

    };
});

NavigationController:

app.controller("navCon", ["$scope", "navigationService", function($scope, navigationService){
    var conNav = this;
    this.page = navigationService.page;  
    navigationService.changePage("login"); //initializing the service page variable as "login" also fails

    this.digest = function(){//perform action whenever a digest cycle runs

        console.log(conNav.page);
    }
}]);

Upon running the page, the log displays:

login
undefined
undefined
undefined

The section where the page is shown/hidden and the 'digest' function is invoked:

<div class="container-fluid" ng-show="{{nav.page == 'home'}}">
    <div class="row" ng-class="{'go':nav.digest()}"><!--go used to trigger a function with each digest-->

New to Angular and unsure what's causing the 'undefined' page issue after the first log. Any guidance on resolving this would be greatly appreciated.

Thank you in advance

Answer №1

It is important to utilize the controller as syntax in this scenario, evident by your usage of this for accessing the controller instance.

The issue at hand lies in the fact that you are trying to access

navigationService.page

prior to initializing it with

navigationService.changePage("login")

Make sure to invoke the service method before attempting to retrieve the service property.

Answer №2

If you want to monitor $stateChange events within your controller, simply listen for them and invoke your service function accordingly.

Answer №3

Initially, I encountered an issue where the changes made to the service did not seem to persist. Upon further investigation, I discovered that the service itself was indeed persistent, but the controller was failing to update accordingly.

To resolve this issue, I implemented the following solutions:

  • Added a watch in the 'navcon' section
  • Repositioned certain lines of code to register the watch after initializing the variable
  • Subsequently, I invoked the changePage method from the service

    this.page = "login";
    $scope.$watch(function(){ return navigationService.page;}, function(){
        console.log("service changed");
        conNav.page = navigationService.page;
    })
    
    navigationService.changePage("login");
    

Additionally, for reasons unknown to me at the time, I had to modify the usage of ng-show directives to utilize ng-if instead.

As a result of these adjustments, the navigation functionality now operates as intended.

I would like to express my gratitude to everyone who provided assistance throughout this process.

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

What is the best way to switch visibility settings for images in a React and Ant Design project?

I'm in the process of developing a page to showcase badges as part of the gamification elements in my project. Currently, I'd like to display a 'grey' badge for users who haven't unlocked it yet. Here's an example: https://i. ...

Handling events with ReactJS can be made even more powerful by passing parameters to

Just dipping my toes into the world of ReactJs and I've put together a component to display a list of buses. My goal is to enable edit and delete functionality for each bus, but I'm struggling to pass the corresponding busId to my edit/delete met ...

What is causing my component callback to not function properly?

I'm currently following a tutorial on AngularJS callbacks from . In my code at https://plnkr.co/edit/dxyI0p0pZFZdMalLfvXO?p=preview, I've attempted to showcase the issue I'm encountering. I have initialized the component in three different w ...

Display an iframe using React in multiple areas across the app with the same state

Within my React scenario, we display a BI dashboard using an iframe on the page, allowing users to interact with the frame and potentially filter the BI data. I've developed a feature that enables this iframe to expand into a full-screen dialog for en ...

What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to ...

Adding a class to a div upon loading: A guide

Currently using the following script: $(document).ready(function() { $(".accept").change(function () { if ($(this).val() == "0") { $(".generateBtn").addClass("disable"); } else { $(".generateBtn").remove("dis ...

Tips for choosing the initial link within a parent list entry

I am working with a jQuery accordion and have a specific need to remove the href attribute from the parent li element without affecting its children. This task requires precision in targeting only the parent li. var parent = $("#quicklaunch ul > li:has ...

Does anyone know of a JavaScript library that uses degrees instead of radians for calculations?

Among the myriad of questions posed here, many are inquiring about converting the output of functions like Math.atan() into degrees for use in CSS transforms or OpenGL. The solution is a simple calculation (180/Math.PI)--yet it requires writing additional ...

Difficulty encountered when deploying cloud function related to processing a stripe payment intent

I've been troubleshooting this code and trying to deploy it on Firebase, but I keep running into a CORS policy error: "Access to fetch at ... from origin ... has been blocked by CORS policy." Despite following Google's documentation on addressin ...

If a user cancels, the radio button in Vue 3 will revert back to

I'm encountering a problem with radio buttons in vue 3. When passing an object from the parent component to the child for data display, I want to set one version as default: <template> <table> ... <tr v-for="(v ...

Creating Highcharts using Three.jsWould you like to know how to render

Recently delving into Three.JS, my goal is to create a 2D Highchart on one of the faces of a cube. While I have successfully drawn the cube and applied an image to it, I am unsure on how to integrate Highchart with this setup. ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

Execute the php code once more following a database row update

Is it possible to rerun a PHP line after updating a table in the database? I have an HTML button that triggers a jQuery post request: btn.onclick = function(e) { $.post('inc/pstPts.php', { pts: pts }); } I ...

What could be the reason for the absence of warning and success messages in this code?

When using AngularJS to validate an email form, I encountered an issue where the "spans" do not display when the form is either invalid or valid. This problem occurs when I remove ng-app="" from the body tag, causing the spans to always show up regardles ...

Controller detects $broadcast() event triggered twice from Angular $rootScope

Triggering a broadcast event on button click: $scope.onButtonClick = function(){ $rootScope.$broadcast('onButtonClick'); } And listening for the event in another controller: $rootScope.$on('onButtonClick',function(event){ alert ...

"Utilizing Webpack for managing relative file paths and implementing multi-slash paths in routes

Recently, I ran into a problem while setting up multi-slash routing paths for my react application with webpack and Node.js on the backend. The issue arose when I defined the following path in my routing: // header {[1, 2, 3, 4, 5].map((id) => ( &l ...

Transmit blob information to node server using fetch, multer, and express

Currently facing an issue with sending a blob object to my node server. The scenario is that on the client side, I am recording some audio using MediaRecorder and then attempting to transmit the file to my server for further processing. saveButton.o ...

utilize jQuery to load webpage with an HTML dropdown element

Querying the Campaigns: // Getting the campaigns $campaigns = $wpdb->get_results( "SELECT * FROM tbl_campaigns ORDER BY campaignID DESC", OBJECT_K ); // Displaying the Cam ...

React: asynchronous setState causes delays in updates

Currently learning React.js, I am working on creating a simple combat game. In my code snippet below, I attempt to update the state to determine whose turn it is to strike: this.setState({ whoseRound: rand }, () => { console.log(this.state.whoseRo ...

The express-fileupload throws an error saying "ENOENT: unable to locate the file or directory at 'public/images/name.ext'"

I am encountering an error ENOENT: no such file or directory, open 'public/images/name.ext from express-fileupload. I have searched for solutions to this issue, but none of the ones I found seem to work for me. Here are two examples: No such file or d ...