I have a simple multi-view Angular application that implements a wizard, so each time a user clicks "Next" button, the app navigates to the next view, and same for "Back" button. I have a $routeProvider config that binds all views to the same controller. Each view represents a chunk of a huge form with input fields, and $routeProvider manages navigation across them:
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/salespoints', {
templateUrl: 'salespoints',
controller: 'main'
})
.when('/users', {
templateUrl: 'users',
controller: 'main'
})
.otherwise({
templateUrl: 'partner',
controller: 'main'
});
$locationProvider.hashPrefix('');
}]);
The problem is that each time a user clicks "Next" or "Back", the controller is invoked, so all the $scope changes that were made on previous steps are simply lost:
app.controller('main', ['$scope', function ($scope) {
console.log('controller invoked'); // appears each time a user presses "Next" or "Back", hence re-instantiation of $scope
}]);
The application is small enough to turn to $rootScope in case every other method fails, but I just would like to avoid that as an anti-pattern.
What's the best way to keep $scope in latest state, with all changes made from the very beginning of app instance's lifecycle, and without re-instantiating it on every change of view?
Use a service to keep your form data and inject it into your controller.
angular.module('app').factory('formService', function () {
var data = {};
return {
data: data
};
});
angular.module('app').controller('ctrl', function(formService) {
this.formData = formService.data;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With