ionic framework - AngularJS - Update a variable of a factory from a controller -
i developping web app ionic 1 , angularjs 1.
in factory (userfact) :
.factory('userfact', function() { var user = []; return { 'setuser': function(user) { this.user = user; console.log('(2) user set: ' + this.user); console.log('(3) user id now: ' + this.user.uid); }, 'updatesport': function(sportid, registered) { console.log('update sport: ' + sportid + ' --> ' + registered); console.log('(4) user uid: ' + this.user.uid); var ref = firebase.database().ref('users/' + this.user.uid + '/sports/'); // sync down server var list = []; ref.on('value', function(snap) { list = snap.val(); }); if(registered) { list.splice(0, 0, {id: sportid}); } else { } ref.set(list); } }; })
in controller :
function ($scope, $stateparams, $state, databasefact, userfact) { // variables $scope.sports = []; $scope.sports = databasefact.getsports(); // functions $scope.updatesport = userfact.updatesport; // execution firebase.auth().onauthstatechanged(function(user) { if (user) { userfact.setuser(user); console.log('(1) ctrl user uid: ' + user.uid); } }); }
according console: logs (1), (2) , (3) display userid form db (4) undefined...
any idea?
thanks
update:
manuel, sorry, think had missed point of question. correct, using factory/service, correct way store state of application. above, not see reason code not work. user must getting re-assigned elsewhere seeing undefined in (4), if not seeing same in (3). simplicity sake, removed references firebase , created working demo: https://plnkr.co/edit/van7ysche8ggrqmzgfsa?p=preview
while demo may not solve problem, hope illustrates factory variable (user) persisted in memory , usable across multiple factory method calls.
original answer (missed point) below:
update state change handler save user on controller scope:
firebase.auth().onauthstatechanged(function(user) { if (user) { $scope.user = user; userfact.setuser(user); console.log('(1) ctrl user uid: ' + user.uid); } });
then, in template, invoke updatesport method, using user scope variable:
updatesport(user, true);
or
updatesport(user, false);
Comments
Post a Comment