Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the modified state of an AngularJS application to the URL

I've got a rather complex HTML form that users fill in and submit. On submit we redirect to a third party Web site, generating that redirect parameters depending on the form values. Then, if users aren't satisfied with the results on the third party Web site, they press the browser's "Back" button, and return to the form. At this point they'd expect to see the form controls in the state they left them before the redirect.

In Backbone.js I could call app.navigate("/form-view/STATE-OF-THE-FORM-SERIALIZED") before the redirect, and the form's state would be saved to the browser's history – in the URL fragment. How would I go about implementing the same behavior for AngularJS? I've read about $location service, but it doesn't provide that kind of functionality. When I call path(SMTH) on it, it always triggers the route handler; and that's not what I want, as I must redirect to an external page at that point.

like image 954
Ivan Krechetov Avatar asked Dec 28 '25 11:12

Ivan Krechetov


1 Answers

You can either serialize it in JSON (or QueryString) form. Do that first and then build up the URL with the parameter as apart of the URL.

Make sure you have two URLs: 1 for the form without any data and another for when it has data.

$routeProvider.when('/form-data', { ... });
$routeProvider.when('/form-data/:data', { ... });

Then setup a submit function to handle passing the data around.

$scope.submit = function() {
  var formData = JSON.stringify($scope.myModel);

  //redirect to internal angularjs page
  $location.path('/form-view/' + formData);

  //or redirect to a local external page
  $window.location = '/form-view/' + formData;
};

And for the controller which handles the /form-data/:data route, use $routeParams to gain access to the :data param in the URL.

If you want it to popup in another page then you'll need to make your own directive which hijacks the form submission event and changes the "action" attribute to change it to the serialized format before the native submission is handled.

like image 84
matsko Avatar answered Dec 30 '25 23:12

matsko