The maximum number of $digest() iterations (10) has been exceeded in $rootScope. Exiting the process

Using UI-Router, I need to check the existing token every time a state change is initiated. The issue only occurs on the initial page load, and disappears upon refreshing the page.

Below is the code snippet that I suspect might be causing the error:

.run(['$rootScope', '$location', '$state', '$http', '$window', 'APIROOT', function ($rootScope, $location, $state, $http, $window, APIROOT) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        var isLogin = toState.name === "login";
        if (isLogin) {
            return;
        }
        var userInfo = $window.sessionStorage.token;
        if (!userInfo) {
            event.preventDefault();
            $state.go('login');
        } else {
            $http.get(APIROOT + 'check_token').then(function(resp){
                return true;
            }).then(function(err){

            })
        }
    });
}]);

My Controller:

angular.module('app')
.controller('AppCtrl', ['$http', '$scope', '$window', 'APIROOT', AppCtrl]);

function AppCtrl($http, $scope, $window, APIROOT) {
    var date = new Date();
    var year = date.getFullYear();

    $scope.main = {
       name: $window.sessionStorage.getItem('name'),
       brand: 'Brand',
       year: year
    };
}

The first solution I found was to change "$stateChangeStart" to "$stateChangeSuccess", but I prefer to perform the check before the state changes successfully. What should I fix?

Answer №1

I discovered that my AppCtrl function is attempting to call $window.sessionStorage.getItem('name') when 'name' is undefined.

To fix this issue, I made the following adjustment:

angular.module('app')
.controller('AppCtrl', ['$http', '$scope', '$window', 'APIROOT', AppCtrl]);

function AppCtrl($http, $scope, $window, APIROOT) {
    var date = new Date();
    var year = date.getFullYear();
    if ($window.sessionStorage.getItem('name')) {
        var name = $window.sessionStorage.getItem('name');
     } else {
        var name = "";
     }
    $scope.main = {
       name: name,
       brand: 'Brand',
       year: year
    };
}

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

Tips for concealing scrollbars across various browsers without compromising functionality

Is there a way to hide the scrollbar functionality on a horizontal scrollbar without using "overflow: hidden"? I need to maintain JS functionality and ensure compatibility with all modern browsers. $j = jQuery.noConflict(); var $panels = $j('#primar ...

Disabling cache in AngularJS is being overridden by Chrome's cache

I'm currently encountering an interesting caching issue while using Chrome. My angularjs service looks like this: var url = '/api/acts/' + accountId + '/policy/?filter=NEW_POLICY'; return $http({ ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

The presence of the !doctype html tag completely messes up my

I am currently working on a code snippet that is supposed to provide the screen coordinates of a given object: <!DOCTYPE HTML> <html> <head> </head> <body style="margin:0px;padding:0px;"> <div id="help" style="top:100px;r ...

Utilize localstorage with Redux and Next.js to initialize the state

Having an issue when attempting to populate the initial state from local storage in order to create a store. I encountered the following error message: ReferenceError: localStorage is not defined Here is my store configuration: const store = createStore(r ...

Troubleshooting AngularJS Directives' Cross-Origin Problems within Eclipse

Hello, I am facing an issue while using Angular JS in Eclipse. Specifically, when attempting to use Directives, I encounter a problem with the Cross-Origin Resource Sharing (CORS) policy when loading the Directives template in the index.html file. XMLHttp ...

Encountered an error while loading resource: server returned a 500 status (Internal Server Error) - A NodeJs Express and MongoDB Web Application hit a snag

I am currently in the process of developing a web application using NodeJS Express and MongoDB. However, I have encountered an issue while attempting to implement AJAX functionality to load and display comments on the post page. The "post-detail" page is ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

Looking for giphy link within a v-for loop (Vue.js)

I am fetching a list of movie characters from my backend using axios and rendering them in Bootstrap cards. My objective is to search for the character's name on Giphy and use the obtained URL as the image source for each card. However, when I attemp ...

Find and retrieve all data attributes with JavaScript

What is the method to retrieve all data-attributes and store them in an array? <ul data-cars="ford"> <li data-model="mustang"></li> <li data-color="blue"></li> <li data-doors="5"></li> </ul> The resultin ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...

When the wireframe property is set to true, the react-three-renderer will only render geometry using the <meshBasicMaterial>

I am new to using the three.js library along with react-three-renderer. I have encountered a problem where only geometry renders when the wireframe property is set to true. If the wireframe property is false (which is the default setting), I expect the mes ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...

What is the best approach for retrieving values from dynamically repeated forms within a FormGroup using Typescript?

Hello and thank you for taking the time to read my question! I am currently working on an Ionic 3 app project. One of the features in this app involves a page that can have up to 200 identical forms, each containing an input field. You can see an example ...

Whenever I use jQuery to dynamically add a new form input, the Select2 input fails to function properly

For my form, I'm attempting to dynamically add a new form-row each time the user clicks the add button. <div class="form-row mb-2"> <div class="form-group col-md-3 my-2"> <label>File</label> ...

SQL inputs with information that updates automatically / autofill SQL input boxes

Is it feasible to create a webpage that can connect to an SQL database, retrieve information from a table, and display it in a text box based on the input provided in another text box? Essentially, I am looking for a way to enable autofill functionality. I ...

The data is not retrieved in the response

When creating an order, I am encountering an issue where the code is not waiting for the meal data retrieval despite using async and await. This results in my response containing empty data. Although I prefer to use async and await over promises for consi ...

Adjusting the size of HighCharts HighMaps with a custom function

Simple query here (I believe) I have a DIV with the class "container" acting as my Map. The Highcharts plugin I'm using is responsive, but it only resizes when the window does. I'm looking to manually trigger a resize without adjusting my windo ...

Retrieve the current row by clicking the button

I've been struggling to retrieve a specific value from a row displayed on my PHP webpage. My objective is to obtain the current value from a particular cell in the row, but using getElementsByTagName has not been successful as it only returns an HTMLC ...

Collapse the columns and set them to float on the left side

My current setup might not be the most visually appealing, but it gets the job done. I have several col-md-4 tags in place. The issue arises when the height of the first tag is larger than the ones next to it, causing the subsequent tag to appear in the mi ...