ajax - Angular ui router (extras) $stateChangeStart event trigger twice -
can explain me why angular ui router extras addition trigger twice (on init!) $statechangestart
event in case when have async ajax check , e.preventdefault()
call?
short event code example:
$rootscope.$on("$statechangestart", function (e, tostate, toparams, fromstate, fromparams, error) { console.log("$statechangestart");//fired twice if(!user.data) { e.preventdefault(); $http.get("https://randomuser.me/api/") .success(function(data, status, headers, config) { console.log(data); user.data = data; $state.go(tostate, toparams); }); } });
without extras addition working expected.
tnx
angularjs has multiple checks during digest cycle check before , after changes, may part of cycle.
you can see behavior during $watch.
$scope.$watch('myvariable', function( change ){ if( !change ){ return; } // important things here. });
during first round of digest change parameter come in undefined, until myvariable set somewhere else. once myvariable set else-wear, $watch fire again , break through if block real work.
if case function, perhaps can add if block , return if 1 or more of parameters undefined, or value not execute on.
$rootscope.$on("$statechangestart", function (e, tostate, toparams, fromstate, fromparams, error) { if( !e || !tostateforexample || anotherparameter ){ return; } console.log("$statechangestart");//fired twice if(!user.data) { e.preventdefault(); $http.get("https://randomuser.me/api/") .success(function(data, status, headers, config) { console.log(data); user.data = data; $state.go(tostate, toparams); }); } });
Comments
Post a Comment