stateChangeStart event called twice per instance of controller - angularjs

I am trying to implement a "notify unsaved changed" solution in angularjs.
Basically I have a BaseForm controller where I listen to the stateChangeStart event. When fired I check if the firm is dirty and if, when prompted, the user confirms to change location. If he doesn't than I preventDefault().
Here is the code I used to achieve this :
this.$scope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) => {
let dirtyForms = this.detailForms.filter((form) => { if (form) { return form.$dirty } });
if (dirtyForms.length && !confirm("Are you sure to leave this page?")) {
event.preventDefault();
}
});
For some reason however, if I navigate to a state managed by the same instance of controller the event is fired twice and therefore I get prompted twice.
Why is this happening? How can I prevent it?

I haven't tried this, but it's a pattern we use. Register your $stateChangeStart as you have (I'm shortening it for simplicity's sake) but with a minor modification:
const deregisterStateChangeStart =
this.$scope.$on('$stateChangeStart', this.foo.bind(this));
I'm assuming you do this in the $onInit() of the controller. Then add this:
this.$scope.$on('$destroy', () => {
deregisterStateChangeStart();
});

Related

Angular reload service when state change or jQuery run for all state (ui.router lib)

I have two issues.
The First one is:
I have try jQuery code and angular.service code for the same thing. To clear input fields from blank spaces dynamically.
$('input[type="text"]').change(function () {
if (!this.value.replace(/\s/g, '').length) {
this.value = "";
}
});
or
angular.module('app').service('nospace', function () {
$('input[type="text"]').change(function () {
if (!this.value.replace(/\s/g, '').length) {
this.value = "";
}
});
});
When i try to use jQuery globally for all angular pages is not working.
When i try to use .service is working, but when i change state is stop working, till i refresh page. I try to add to
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {}); and call the service from there when state is changed to fix this problem, but still don`t work properly.
I added to controller like this
angular.module('app').controller('channelAoiEditor', function (..,.., nospace) { ... some code ... }
Second issue is with parsing the url to state properly.
I have this state:
.state('edit', {
url: '/EditCustomer/:id',
templateUrl: 'Client/app/customers/editCustomer/editCustomer.html',
controller: 'editCustomer'
})
When I'm in "Edit Customer" page and try to change the user directly from the url. Page reload, but retains last used user instead of reloaded the new user, but the URL is the same as new one.
I try with changing the state with:
url: '/EditCustomer/{id}'
or
url: '/EditCustomer/{id:[a-zA-Z0-9/.]*}'
On $rootScope.$on('$locationChangeSuccess', function (event, url, oldUrl, state, oldState) {..} I get the changes but how to parse it properly to change the content.
Thank You!
Perhaps you need to $scope.$apply() and (or) $scope.$digest() for reloading the page... it happens that jQuery and Javascript code is turn based so in order to "repaint" the page you need to:
$apply and $digest
That step that checks to see if any binding values have changed actually has a >method, $scope.$digest(). That’s actually where the magic happens, but we >almost never call it directly, instead we use $scope.$apply() which will call >$scope.$digest() for you.
so I would encapsulate the code as this:
$scope.$apply(function(){
$('input[type="text"]').change(function () {
if (!this.value.replace(/\s/g, '').length) {
this.value = "";
}
});
That way you ensure that you are applying and updating the values.
There is some documentation here http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
See ya :)
I managed to fix it I had forgotten an important difference on jQuery, which is the following
$(document).on('change', 'input[type="text"]', AddVerification)
and
$('input[type="text"]').change(AddVerification);
This is how I fix it
function AddVerification() {
if (!this.value.replace(/\s/g, '').length) {
this.value = "";
}
}
angular.modul('app',[....])
.service('nospace', function () {
//jQuery trim input fields
this.clearWhiteSpaces = function myfunction() {
$(document).off("change", 'input[type="text"]', AddVerification)
.on('change', 'input[type="text"]', AddVerification);
}
}).run(
['$rootScope', '$state', '$stateParams','nospace',
function ($rootScope, $state, $stateParams,nospace) {
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
nospace.clearWhiteSpaces();
});
})
and for the controller:
angular.module('app').controller('channelAoiEditor', function ($scope, datastore, $cookieStore, modalWindow, nospace) {
Remained the problem with passing properly the URL to $stateProvider.state

Stuck in a loop when using $scope.on('$stateChangeStart')

Before a user navigates away from the current state I want to prompt them to save their work. I've got a listener on $stateChangeStart but the problem is, after the user has confirmed their desire to leave the current state they get prompted again and can't leave because the listener keeps intercepting the state change. I tried passing a boolean parameter through so I could check if they confirmed their intent to leave, but it doesn't come through.
$scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
console.log('toState: ');
console.log(toState);
console.log('toParams: ');
console.log(toParams);
console.log('fromState: ');
console.log(fromState);
console.log('fromParams: ');
console.log(fromParams);
console.log('options: ');
console.log(options);
//if (!isExitConfirmed) {
event.preventDefault();
ModalFactory.OpenTwoActionModal('EventFooterTwoActionModal',
'Exit Event', 'Are you sure you want to exit? Any unsaved changes will be lost.',
'Exit', function() { $state.go(toState, { isExitConfirmed: true }); },
'Cancel', function() {});
//}
});
I've logged to the console toState, toParams, fromState, fromParams and options but none of them contain isExitConfirmed.
What am I missing here, or am I going about this the wrong way?
I suggest you to use resolve in state providers configuration instead of listening to the event. Event handlers are always not good practice to use because it causes memory leak.
Before you call stage.go(), invoke a popup for saving the data. once user confirms it, save the flag. Access the flag in resolve of next route change in state provider configuration.
Use deferred objects from the $q service, and the related promises.
Promises can be consumed only once, and they can be resolved or rejected.

How can I inject custom data like factory in the ui router stateChangeStart function

I am calling this:
$state.go("main.projects.selected.dates.day", { id: $state.params.id }, {reload: true});
I would really like to pass custom data from the state.go function to the stateChangeStart function. This is possible with the state params - which I could abuse to accept a date object - but then my url would not work anymore correctly...
How can I pass data from state.go to stateChangeStart? Just by hacking the rootScope.customData property?
$rootScope.$on('$stateChangeStart', function (ev, toState, toParams, fromState, fromParams, injectCustomFactory here)
{
// Run custom logic here on the injected custom factory
// then change the toParams.customData property by assigning the injected value to this property.
}
WHY do I have to run this logic in the stateChangeStart you might ask.
Its because only there I can check wether the user changed the url actively ($rootScope.customData is then falsy) or a state.go is done from outside and before I do a $rootScope.customData = MyValueLogic;
Inject it in the run (or wherever you're watching $stateChangeStart):
angular.module('lalala').run(function ($rootScope, factory) {
$rootScope.on('$stateChangeStart', function (e, toState, ...) {
factory.doSomething();
});
});

ui-router resume preventedEvent

I want users to be notified that they have to save changes when they navigate to another page.
Therefore I listen to the stateChangeStart Event of UI-ROUTER.
I need to prevent the event to prevent, that the next page doesn't load the values before they are saved. When I manually navigate to the desired page via $state.go(..) I keep hanging in a loop of stateChangeStart Events
$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
var confirmPopup = $ionicPopup.confirm({
....
});
confirmPopup.then(function(res){
....
}
$ionicNavBarDelegate.back();
});
});
How to log of the stateChangeStart-Event?
Edit:
$urlRouter.sync();
$state.go(toState.name, {id:toParams.id}, {reload: false});
Stays inside the loop.
$urlRouter.sync()
Returns null.
Triggers an update; the same update that happens when the address bar
url changes, aka $locationChangeSuccess. This method is useful when
you need to use preventDefault() on the $locationChangeSuccess event,
perform some custom logic (route protection, auth, config,
redirection, etc) and then finally proceed with the transition by
calling $urlRouter.sync().
See docs.
The use of the urlRouter.sync() is pretty obvious if you look at the docs, if you want to go to another state or want to check something in between the transition, you could also do this to prevent a redirect loop:
var nextState = null;
$rootScope.$on('$stateChangeStart', function (event, next, current) {
if (next.name == nextState) return;
event.preventDefault();
nextState = next.name;
$state.go(next.name);
});

stop angular-ui-router navigation until promise is resolved

I want to prevent some flickering that happens when rails devise timeout occurs, but angular doesn't know until the next authorization error from a resource.
What happens is that the template is rendered, some ajax calls for resources happen and then we are redirected to rails devise to login. I would rather do a ping to rails on every state change and if rails session has expired then I will immediately redirect BEFORE the template is rendered.
ui-router has resolve that can be put on every route but that doesn't seem DRY at all.
What I have is this. But the promise is not resolved until the state is already transitioned.
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
//check that user is logged in
$http.get('/api/ping').success(function(data){
if (data.signed_in) {
$scope.signedIn = true;
} else {
window.location.href = '/rails/devise/login_path'
}
})
});
How can I interrupt the state transition, before the new template is rendered, based on the result of a promise?
I know this is extremely late to the game, but I wanted to throw my opinion out there and discuss what I believe is an excellent way to "pause" a state change. Per the documentation of angular-ui-router, any member of the "resolve" object of the state that is a promise must be resolved before the state is finished loading. So my functional (albeit not yet cleaned and perfected) solution, is to add a promise to the resolve object of the "toState" on "$stateChangeStart":
for example:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
toState.resolve.promise = [
'$q',
function($q) {
var defer = $q.defer();
$http.makeSomeAPICallOrWhatever().then(function (resp) {
if(resp = thisOrThat) {
doSomeThingsHere();
defer.resolve();
} else {
doOtherThingsHere();
defer.resolve();
}
});
return defer.promise;
}
]
});
This will ensure that the state-change holds for the promise to be resolved which is done when the API call finishes and all the decisions based on the return from the API are made. I've used this to check login statuses on the server-side before allowing a new page to be navigated to. When the API call resolves I either use "event.preventDefault()" to stop the original navigation and then route to the login page (surrounding the whole block of code with an if state.name != "login") or allow the user to continue by simply resolving the deferred promise instead of trying to using bypass booleans and preventDefault().
Although I'm sure the original poster has long since figured out their issue, I really hope this helps someone else out there.
EDIT
I figured I didn't want to mislead people. Here's what the code should look like if you are not sure if your states have resolve objects:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
if (!toState.resolve) { toState.resolve = {} };
toState.resolve.pauseStateChange = [
'$q',
function($q) {
var defer = $q.defer();
$http.makeSomeAPICallOrWhatever().then(function (resp) {
if(resp = thisOrThat) {
doSomeThingsHere();
defer.resolve();
} else {
doOtherThingsHere();
defer.resolve();
}
});
return defer.promise;
}
]
});
EDIT 2
in order to get this working for states that don't have a resolve definition you need to add this in the app.config:
var $delegate = $stateProvider.state;
$stateProvider.state = function(name, definition) {
if (!definition.resolve) {
definition.resolve = {};
}
return $delegate.apply(this, arguments);
};
doing if (!toState.resolve) { toState.resolve = {} }; in stateChangeStart doesn't seem to work, i think ui-router doesn't accept a resolve dict after it has been initialised.
I believe you are looking for event.preventDefault()
Note: Use event.preventDefault() to prevent the transition from happening.
$scope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
event.preventDefault();
// transitionTo() promise will be rejected with
// a 'transition prevented' error
})
Although I would probably use resolve in state config as #charlietfl suggested
EDIT:
so I had a chance to use preventDefault() in state change event, and here is what I did:
.run(function($rootScope,$state,$timeout) {
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
// check if user is set
if(!$rootScope.u_id && toState.name !== 'signin'){
event.preventDefault();
// if not delayed you will get race conditions as $apply is in progress
$timeout(function(){
event.currentScope.$apply(function() {
$state.go("signin")
});
},300)
} else {
// do smth else
}
}
)
}
EDIT
Newer documentation includes an example of how one should user sync() to continue after preventDefault was invoked, but exaple provided there uses $locationChangeSuccess event which for me and commenters does not work, instead use $stateChangeStart as in the example below, taken from docs with an updated event:
angular.module('app', ['ui.router'])
.run(function($rootScope, $urlRouter) {
$rootScope.$on('$stateChangeStart', function(evt) {
// Halt state change from even starting
evt.preventDefault();
// Perform custom logic
var meetsRequirement = ...
// Continue with the update and state transition if logic allows
if (meetsRequirement) $urlRouter.sync();
});
});
Here is my solution to this issue. It works well, and is in the spirit of some of the other answers here. It is just cleaned up a little. I'm setting a custom variable called 'stateChangeBypass' on the root scope to prevent infinite looping. I'm also checking to see if the state is 'login' and if so, that is always allowed.
function ($rootScope, $state, Auth) {
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
if($rootScope.stateChangeBypass || toState.name === 'login') {
$rootScope.stateChangeBypass = false;
return;
}
event.preventDefault();
Auth.getCurrentUser().then(function(user) {
if (user) {
$rootScope.stateChangeBypass = true;
$state.go(toState, toParams);
} else {
$state.go('login');
}
});
});
}
as $urlRouter.sync() doesn't work with stateChangeStart, here's an alternative:
var bypass;
$rootScope.$on('$stateChangeStart', function(event,toState,toParams) {
if (bypass) return;
event.preventDefault(); // Halt state change from even starting
var meetsRequirement = ... // Perform custom logic
if (meetsRequirement) { // Continue with the update and state transition if logic allows
bypass = true; // bypass next call
$state.go(toState, toParams); // Continue with the initial state change
}
});
To add to the existing answers here, I had the exact same issue; we were using an event handler on the root scope to listen for $stateChangeStart for my permission handling. Unfortunately this had a nasty side effect of occasionally causing infinite digests (no idea why, the code was not written by me).
The solution I came up with, which is rather lacking, is to always prevent the transition with event.preventDefault(), then determine whether or not the user is logged in via an asynchronous call. After verifying this, then use $state.go to transition to a new state. The important bit, though, is that you set the notify property on the options in $state.go to false. This will prevent the state transitions from triggering another $stateChangeStart.
event.preventDefault();
return authSvc.hasPermissionAsync(toState.data.permission)
.then(function () {
// notify: false prevents the event from being rebroadcast, this will prevent us
// from having an infinite loop
$state.go(toState, toParams, { notify: false });
})
.catch(function () {
$state.go('login', {}, { notify: false });
});
This is not very desirable though, but it's necessary for me due to the way that the permissions in this system are loaded; had I used a synchronous hasPermission, the permissions might not have been loaded at the time of the request to the page. :( Maybe we could ask ui-router for a continueTransition method on the event?
authSvc.hasPermissionAsync(toState.data.permission).then(continueTransition).catch(function() {
cancelTransition();
return $state.go('login', {}, { notify: false });
});
The on method returns a deregistration function for this listener.
So here is what you can do:
var unbindStateChangeEvent = $scope.$on('$stateChangeStart',
function(event, toState, toParams) {
event.preventDefault();
waitForSomething(function (everythingIsFine) {
if(everythingIsFine) {
unbindStateChangeEvent();
$state.go(toState, toParams);
}
});
});
I really like the suggested solution by TheRyBerg, since you can do all in one place and without too much weird tricks. I have found that there is a way to improve it even further, so that you don't need the stateChangeBypass in the rootscope. The main idea is that you want to have something initialized in your code before your application can "run". Then if you just remember if it's initialized or not you can do it this way:
rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState) {
if (dataService.isInitialized()) {
proceedAsUsual(); // Do the required checks and redirects here based on the data that you can expect ready from the dataService
}
else {
event.preventDefault();
dataService.intialize().success(function () {
$state.go(toState, toParams);
});
}
});
Then you can just remember that your data is already initialized in the service the way you like, e.g.:
function dataService() {
var initialized = false;
return {
initialize: initialize,
isInitialized: isInitialized
}
function intialize() {
return $http.get(...)
.success(function(response) {
initialized=true;
});
}
function isInitialized() {
return initialized;
}
};
You can grab the transition parameters from $stateChangeStart and stash them in a service, then reinitiate the transition after you've dealt with the login. You could also look at https://github.com/witoldsz/angular-http-auth if your security comes from the server as http 401 errors.
I ran in to the same issue Solved it by using this.
angular.module('app', ['ui.router']).run(function($rootScope, $state) {
yourpromise.then(function(resolvedVal){
$rootScope.$on('$stateChangeStart', function(event){
if(!resolvedVal.allow){
event.preventDefault();
$state.go('unauthState');
}
})
}).catch(function(){
$rootScope.$on('$stateChangeStart', function(event){
event.preventDefault();
$state.go('unauthState');
//DO Something ELSE
})
});
var lastTransition = null;
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
// state change listener will keep getting fired while waiting for promise so if detect another call to same transition then just return immediately
if(lastTransition === toState.name) {
return;
}
lastTransition = toState.name;
// Don't do transition until after promise resolved
event.preventDefault();
return executeFunctionThatReturnsPromise(fromParams, toParams).then(function(result) {
$state.go(toState,toParams,options);
});
});
I had some issues using a boolean guard for avoiding infinite loop during stateChangeStart so took this approach of just checking if the same transition was attempted again and returning immediately if so since for that case the promise has still not resolved.

Resources