AngularJS $broadcast $on doesn't work at first time - intermittent issue -
there strange behaviour in angularjs application. use case create user @ "usercreate.html" , after creating (over backend rest- service -> http post) redirect "usercreateresponse.html" made.
i have 2 controllers:
- usercreate.html -> createusercontroller
- usercreateresponse.html -> createuserresponsecontroller
and share data between createusercontroller
, createuserresponsecontroller
on $rootscope.$broadcast
, $rootscope.$on
.
my problem is, when have changed in code (angularjs code) , refresh browser page , afterwards create user, user creation works fine , redirected usercreateresponse.html no values shown -> first time -> if navigate usercreate.html , create user once again works fine.
i found out in case if not working, http made html- code end. in case works http post made works fine.
does know how prevent first user creation -> redirect problem?
here controller/services:
function createusercontroller($scope, createuserservice) { $scope.createuser = function(data) { createuserservice.createuser($scope.usernamecreate, $scope.passwordcreate, $scope.role); } } services.factory('createuserservice', function($rootscope, $location, $http) { ... var res = $http.post('/users/createuser', dataobj); res.success(function(data, status, headers, config) { $rootscope.$broadcast('handlecreateduser', {usernamecreate: data.username, passwordcreate: data.password, role: data.roles}); $location.path("usercreateresponse"); }); res.error(function(data, status, headers, config) { ... }); } return sharedcreateuserservice; }); function createuserresponsecontroller($rootscope) { $rootscope.$on('handlecreateduser', function(event, args) { $rootscope.usernamecreated = args.usernamecreate; $rootscope.passwordcreated = args.passwordcreate; $rootscope.role = args.role[0]; }); }
instead of broadcast, can use service store response of creation of user. can share using service createuserresponsecontroller. broadcast event, might happening is, broadcasting event before controller handles instantiated. so, $on may not have registered till then. , hence issue face.
Comments
Post a Comment