Angular's $location is reverting back after the modification

When using Angular, I encountered an issue where the user was not redirected to the view page after submitting a form.

To handle this, I attached the following function to the scope:

$scope.create = function () {
   return $scope.customer.$save({}, function (obj) {
       Msg.show('Customer created');
       return $location.path('customer/'+obj.id);
   })
};

This method successfully redirects the user as intended.

To further organize the code, I decided to encapsulate the logic within a service.

...
this.create = function (object, params, callback) {
    return function () {
        return object.$save(params, function (obj) {
            Msg.show('Object created');
            if ( callback instanceof Function ) {
                return callback(obj);
            }
        });
    };
};
....

I then attached the service to the scope in this way:

$scope.create = ResourceActions.create($scope.customer, {}, function (customer) {
    return $location.path('customers/'+customer.id);
});

However, after submission, the user is only "redirected" for a split second before the path changes back. It's puzzling and unclear what is causing this behavior.

Answer №1

You mentioned that

Once the user submits, there is a quick redirection that quickly reverts back to the original path.
, indicating a potential issue with redirecting to an incorrect path before entering the otherwise branch:

.otherwise({
    redirectTo: '/**'
})  

I recommend verifying the status of your customer.id to ensure it is not undefined.

Answer №2

Here's a suggestion to update your $scope:

$scope.create = ResourceActions.create($scope.customer, {}, function (customer) {
    $location.path('customers/'+customer.id);
});

You can also try using $state.go. For instance, if you have the following state defined:

.state('customers-details', {url: '/customers/:id'}) 

You could implement $state.go in this manner:

$scope.create = ResourceActions.create($scope.customer, {}, function (customer) {
     $state.go('customers-details', {id: customer.id});
});

Just a reminder, ensure that you inject $state into your controller.

Take care!

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

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

Link to download an Excel spreadsheet

My server is capable of generating excel files dynamically, and I am utilizing AJAX to download these dynamic excel files. Upon successful completion in the callback function, I receive the data for the excel file. $.ajax({ url: exporting. ...

Caution: It is not possible to make changes to a component (`App`) during the rendering of another component (`History

I am currently in the process of creating a tic tac toe game, but I'm encountering an error that is preventing me from updating the history. Despite following a tutorial on skillshare.com and mirroring the steps exactly, the error persists. I must men ...

What could be causing the absence of ReactDOM in my hello world application?

I have recently started learning Reactjs and I'm attempting to run a hello world program in the browser. However, I encountered an error which reads: react-dom.min.js:12 Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_ ...

What is the syntax for defining parameters in an overloaded arrow function in TypeScript?

Trying to create an async arrow function that can handle a single image object or an array of image objects. I'm new to TypeScript overloading and may be approaching this the wrong way. Here's what I've come up with: type ImageType = { ...

MongoDB error codes and their associated HTTP status codes are important for developers to understand

When a new user attempts to sign up with an existing user account, MongoDb triggers a 11000 error code In Express, handling this scenario can be done as follows: async function signup(req, res, next){ try{ // perform some actions }catch(err){ i ...

Mixing success and error states can lead to confusion when using jQuery and Express together

I've been struggling with a simple question that's been on my mind for quite some time. Despite my searches, I haven't found a similar query, so I apologize if it seems too basic or repetitive. The scenario involves an API route (Express-ba ...

Sorting through an array of objects nested within another array of objects

I'm currently working on a MERN app where I retrieve all albums using axios. This is the structure of the data: [ { title: "", artist: "", reviews: [ { username: "", comment: "", }, { ...

The struggle between Node.js 404 errors and Angular's URL refresh issue

I am currently developing a Node.js and AngularJS application. I encountered an issue where a page loads successfully when the URL is entered, but then I added a script to redirect to a 404 error page. Now, only one of the criteria works at a time - either ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Issues with loading content in jQuery's ajax() function

Having an issue with the ajax() function in jQuery. It seems like a simple problem, but I'm struggling to figure it out. My goal is to load content from another HTML file using ajax and here's the code I have so far: $(function(){ $('.submi ...

JavaScript: Unusual behavior discovered in forEach iteration

Here's the code snippet I'm having trouble with: someArray.forEach(x => { // do something console.log(‘calling api for ‘ + x); callAnHttpApiAsync(...); sleep(10); }); The issue lies in the asynchronous nature of the HTTP API call within ...

Backing up a mongodb collection can be easily achieved with the help of express.js and Node.js

I am looking to create a monthly backup of my userdatas collection. The backup process involves: I intend to transfer the data from the userdatas collection to a designated backupuserdatas collection. A batch program should be scheduled to run automatica ...

Error message encountered when using CKEditor in an Angular.js application

While using ckeditor to edit content, I have included the module and linked all necessary files. However, an error is being thrown: TypeError: this[a] is undefined. As a newcomer to Angular, I'm unable to find a solution on my own. Could someone plea ...

Send a request from my own local client without encountering any Cross-Origin Resource Sharing (C

I am attempting to send a request from my locally hosted Node.js/Express.js client to a third-party API that I have deployed on the cloud. Strangely, I keep running into a CORS error whenever I make the request. The interesting part is that the request wor ...

Tips for creating a zoomable drawing

I have been working on this javascript and html code but need some assistance in making the rectangle zoomable using mousewheel. Could someone provide guidance? var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var width ...

Having troubles with the xml2json jQuery plugin's functionality?

I've implemented the jQuery XML to JSON Plugin by Fyneworks.com. Any idea why my code isn't functioning as expected? index.html <!DOCTYPE html> <html> <head> <script src="build/jquery.xml2json.js"></script> <sc ...

What is the AngularJS alternative to $.ajaxPreFilter()?

Looking for help with implementing a similar function in Angular? Below is an example of how you can achieve the same functionality using Angular 1.x: $httpProvider.interceptors.push(function() { return { 'request': function(config) { ...

Constantly showing blank white pages on my website specifically in Internet Explorer 11

I successfully developed a website using react, babel, webpack, and backend Django framework. Everything runs smoothly on Chrome, Safari, and Firefox, but when it comes to IE11, issues arise. Initially, the site functions properly, but after navigating thr ...