Why won't the state change when using Angular's ui-router $state.go method?

I have developed a factory that is responsible for detecting state changes and checking if a form has been modified. When the form is dirty, a modal window like a confirmation prompt should appear. However, I am encountering an issue where the $state.go() method does not seem to work as expected. I am puzzled as to why:

(function() {

    var checkStateChangeService = function ($rootScope, $modal) {

        var addCheck = function ($scope, form, $state) {

            var modalInstanceCtrl = function ($scope, $modalInstance) {
                $scope.ok = function () {
                    $modalInstance.close();
                };

                $scope.cancel = function () {
                    $modalInstance.dismiss("cancel");
                };
            };

            var removeListener = $rootScope.$on('$stateChangeStart',  function (event, toState, toParams, fromState, fromParams) {


                if (form.$pristine) {
                    return;
                }


                event.preventDefault();
                var message = "There are unsaved changes, do you want to continue?";
                var title = "Unsaved Changes";

                var modalHtml = "<div class=\"panel\">\r\n";
                modalHtml += "<h4 class=\"center\" id=\"modalTitle\">" + title + "<\/h4>\r\n";
                modalHtml += "<div class=\"small-12 columns\">\r\n";
                modalHtml += "<div class=\"modal-body\">" + message + "<\/div>";
                modalHtml += "<div class=\"button-box\">\r\n";
                modalHtml += "<button ng-click='ok()' class=\"tiny\">OK<\/button>\r\n";
                modalHtml += "<button ng-click='cancel()' class=\"tiny\">Cancel<\/button>\r\n";
                modalHtml += "<\/div>\r\n";
                modalHtml += "<\/div>\r\n";
                modalHtml += "<\/div>";

                var modalInstance = $modal.open({
                    template: modalHtml,
                    controller: modalInstanceCtrl
                });

                modalInstance.result.then(function () {
                    $state.go(toState);
                }, function () {
                    $state.go(fromState);
                });

            });

            $scope.$on("$destroy", removeListener);
        };

        return { checkFormOnStateChange: addCheck};
    }

    var module = angular.module("traApp");
    module.service("checkStateChangeService", checkStateChangeService);
}());  

Despite no visible errors, I am unable to understand why this functionality is not working properly. Similar implementations have been successful in other examples.

Answer №1

After coming across this helpful question, I was able to tackle the issue at hand. One minor observation is that the modal closes right after the state changes, which might appear a bit odd but it does the job effectively. The insights shared by AvijitGupta really made me pause and reconsider, as it did seem like the state wasn't updating properly.

(function() {

    var checkStateChangeService = function ($rootScope, $modal) {

        var implementCheck = function ($scope, form, $state) {

            var _this = this;

            var modalInstanceCtrl = function ($scope, $modalInstance) {
                $scope.ok = function () {
                    $modalInstance.close();

                };

                $scope.cancel = function () {
                    $modalInstance.dismiss("cancel");
                };
            };

            var removeListener = function (event, toState, toParams, fromState, fromParams) {


                if (form.$pristine) {
                    return;
                }

                _this.toState = toState;
                _this.toParams = toParams;

                var message = "There are unsaved changes, do you want to continue?";
                var title = "Unsaved Changes";

                var modalHtml = "<div class=\"panel\">\r\n";
                modalHtml += "<h4 class=\"center\" id=\"modalTitle\">" + title + "<\/h4>\r\n";
                modalHtml += "<div class=\"small-12 columns\">\r\n";
                modalHtml += "<div class=\"modal-body\">" + message + "<\/div>";
                modalHtml += "<div class=\"button-box\">\r\n";
                modalHtml += "<button ng-click='ok()' class=\"tiny\">OK<\/button>\r\n";
                modalHtml += "<button ng-click='cancel()' class=\"tiny\">Cancel<\/button>\r\n";
                modalHtml += "<\/div>\r\n";
                modalHtml += "<\/div>\r\n";
                modalHtml += "<\/div>";

                var modalInstance = $modal.open({
                    template: modalHtml,
                    controller: modalInstanceCtrl
                });

                modalInstance.result.then(function () {

                    onRouteChangeOff();                    
                    $state.go(_this.toState.name, _this.toParams);
                }, function (error) {

                });

                event.preventDefault();
            };

            var onRouteChangeOff = $rootScope.$on('$stateChangeStart', removeListener);

       };

        return { trackFormChangesOnStateChange: implementCheck};
    }

    var module = angular.module("traApp");
    module.service("checkStateChangeService", checkStateChangeService);
}());

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

Having issues with the Grunt build on Yo Angular

I created an Angular App using the Yo angular-generator tool. Initially, I had no issues building the app with Grunt Build. However, I decided to integrate Bootstrap 3 and also ran npm install grunt-bower-install. To incorporate these changes, I made mod ...

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Show the URL hash as url.com/something#/ rather than url.com/something/#/

I'm encountering a peculiar issue with my Angular v1.6.5 setup. My routes seem to be acting strangely, for example: $routeProvider .when('/', { templateUrl: 'myTemplate', controller: 'myController', method: &apo ...

Extracting address from a string containing HTML line breaks and apostrophes using JavaScript

I need help with parsing an address that is in a string format like the following: "1234 Something Street<br>Chicago, IL 34571<br>" I am struggling to extract and assign it to separate variables: var street = ...; var city = ...; var state = ...

Securely accessing Service Stack REST API with AngularJS and $http.get by providing authentication details

Currently, I am utilizing a service stack web service that has the CorsFeature enabled. My approach involves calling a service using AngularJS's $http.get method while setting withCredentials to true: $http.get(url,{ withCredentials: true}) I am se ...

A plethora of color choices in a Multi-select Box

Hi there! I am facing an issue with dynamically adding multiple select boxes. Currently, I have 4 color-coded options under the selection boxes, which work fine when there is only one box. However, when I add more than one select box, the color coding doe ...

Is there a way to implement Bootstrap 5 toast in Vue.js and navigate to a different page, such as after submitting a form?

Is there a way to incorporate the bootstrap5 toast in vuejs while also redirecting to another page? For example, after submitting a form and being redirected to a new page, I would like a toast message to appear with the statement "Your form has been sub ...

Step-by-Step Guide for Uploading an Entire Folder and Its Contents

I have been working on a code to upload multiple files, but now I am facing the challenge of uploading an entire folder with multiple files and possibly subfolders containing even more files. Currently, I am utilizing JavaScript for obtaining the files and ...

Retrieving the output value from a callback function in Sqlite3

In my current project, I am using Sqlite3 with an Express backend along with a React frontend. My goal is to verify if a user with a specific email exists in the database. While working on the function provided below, which is still a work in progress, I e ...

Using React to simulate API calls outside of testing environments

For instance, I encounter issues when certain endpoints are inaccessible or causing errors, but I still need to continue developing. An example scenario is with a function like UserService.getUsers where I want to use fake data that I can define myself. I ...

Creating an Extjs model for a complex nested JSON structure

Take a look at this JSON structure { "id": 123, "name": "Ed", "orders": [ { "id": 50, "total": 100, "order_items": [ { "id": 20 ...

Guide to indicating the chosen filter in React using Material UI

I'm currently working on a blog that includes a filter feature. The filtering functionality is working perfectly, but I am trying to specify which filter option is currently selected. Here is the code snippet: {cardCategories.map((cat) => { retu ...

What is the best way to utilize the knockout's if and ifnot binding in order to show or hide web elements like divs and other HTML tags?

I'm currently using knockout and attempting to show or hide two buttons based on the value of a boolean called server, but I'm having trouble getting it right. Here is the code I have so far, please help me as I believe there may be something mis ...

What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

Adjustable height for text input field

Is it possible to adjust the height of a textarea dynamically based on user input, rather than relying on scrollbars when content exceeds the width and height of the field? <textarea class="form-control"></textarea> For instance, if a user ty ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...

How to Handle CRUD Errors in NodeJS using Mongoose and Return a Custom Response to the Client

Setup NodeJS 10 MongoDB Client side app : Angular 9 About In my NodeJS application, I have a controller and service that work together to create an entity and return a promise. Here's how it looks: Controller async create(@Body() entityData: an ...

What is the process for importing something from index.js within the same directory?

My folder structure is similar to the one below /components/organisms -- ModuleA.vue -- ModuleB.vue -- index.js The content of index.js: export { default as ModuleA } from "./ModuleA.vue" export { default as ModuleB } from "./ModuleB.vue&qu ...

The functionality of $viewContentLoading appears to be malfunctioning

Before the content is loaded, I'm attempting to log a value. I am using $viewContentLoading within the init function, but the value is not being logged. Can anyone help me identify the issue with my code? var app = angular.module('plunker&apos ...

Accessing an array within angular.forEach is not permitted

Recently, I've been pulling data from a factory using express and MongoDB with mongoose defined on a model. While I can successfully retrieve the document by its ID and have it within the scope, my challenge lies in iterating through the array of crew ...