AngularJS - Update a variable of a factory from a controller - angularjs

I am developping a web app with Ionic 1 and AngularJS 1.
In my 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 is now: ' + this.user.uid);
},
'updateSport': function(sportid, registered) {
console.log('Update sport: ' + sportid + ' --> ' + registered);
console.log('(4) For user uid: ' + this.user.uid);
var ref = firebase.database().ref('users/' + this.user.uid + '/sports/');
// sync down from server
var list = [];
ref.on('value', function(snap) { list = snap.val(); });
if(registered) {
list.splice(0, 0, {id: sportid});
} else {
}
ref.set(list);
}
};
})
In my 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 to the console: logs (1), (2) and (3) display a userid form my db but (4) is always undefined...
Any idea?
Thanks

UPDATE:
Manuel, sorry, I think I had missed the point of your question. You are correct, using a factory/service, is the correct way to store the state of your application. From the above, I do not see a reason for your code not work. The user must be getting re-assigned elsewhere for you to be seeing undefined in (4), if you are not seeing the same in (3). For simplicity sake, I removed references to firebase and created a working demo: https://plnkr.co/edit/vaN7ySche8GgRQmZgFsa?p=preview
While the demo may not solve your problem, I hope it illustrates that the factory variable (user) is persisted in memory and usable across multiple factory method calls.
ORIGINAL ANSWER (MISSED THE POINT) BELOW:
Update the state change handler to save the user on the 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 the template, invoke the updateSport method, using the user scope variable:
updateSport(user, true);
or
updateSport(user, false);

You need to pass the arguments while calling updateSport in controller,
$scope.updateSport = UserFact.updateSport(userid,registered);

Related

Angular chat client - 2 views with one controller

I build chat function in my web app and i am about to create chat functionality between logged clients. Here is my screen from application to show exactly what i want to solve
Screen of my app
As you can see i got list of online users stored in scope in sidebar. Its created as partial view in my Asp.Net with .cshtml and i render content in "white box" using angular routing.
Problem is i use same controller twice and it creates new scope for each html so i got data in my sidebar, but in my content view i dont have any data. I am thinking about passing my data to rootscope, but i dont know if its good idea.
So my question is. Is there anything how i can clone my data from one controller to another or how i can solve this without changing functionality and if i can keep my views controlled with one controller.
Here is my PrivateChatController.js
(function () {
'use strict';
app.controller('PrivateChatController', ['$rootScope', '$scope', 'SignalRService', '$location', 'PrivateChatService', PrivateChatController]);
function PrivateChatController($rootScope, $scope, SignalRService, $location, PrivateChatService) {
//angular stuff
$scope.online_users = [];
$scope.isChatHidden = false;
$scope.openPrivateChatWindow = function (index) {
// $scope.isChatHidden = true;
angular.forEach($scope.online_users, function (value, key) {
if (index == key) {
$rootScope.currentPrivateChatUser = ({
UserName: value.UserName,
ConnectionId: value.connectionId,
});
$location.path("/details/" + value.UserName);
}
});
};
$scope.closePrivateChatWindow = function (index) {
$scope.isChatHidden = false
};
//signalR stuff
var chatHub = $.connection.chatHub;
$.connection.hub.logging = true;
chatHub.client.foo = function () { };
registerClientMethods(chatHub);
$.connection.hub.start()
.done(function(){ console.log('Now connected, connection ID=' + $.connection.hub.id); })
.fail(function () { console.log('Could not Connect!'); });
function registerClientMethods(chatHub) {
//user object
chatHub.client.newOnlineUser = function (user) {
var newUser = ({
connectionId: user.ConnectionId,
UserName: user.UserName
});
$scope.online_users.push(newUser);
$scope.$apply();
};
//compare scope online users with server list of online users
chatHub.client.getOnlineUsers = function (onlineUsers) {
//loop through scope
angular.forEach($scope.online_users, function (scopeValue, scopeKey) {
//loop through received list of online users from server
angular.forEach(onlineUsers, function (serverListValue, serverListKey) {
if (!(serverListValue.ConnectionId == scopeValue.connectionId)) {
var newUser = ({
connectionId: serverListValue.ConnectionId,
UserName: serverListValue.UserName
});
$scope.online_users.push(newUser);
$scope.$apply();
}
})
})
};
chatHub.client.onUserDisconnected = function (id, user) {
var index = 0;
//find out index of user
angular.forEach($scope.online_users, function (value, key) {
if (value.connectionId == id) {
index = key;
}
})
$scope.online_users.splice(index, 1);
$scope.$apply();
};
}};})();
Consider using services as a layer for data sharing. It should also contain chat related logic, in my opinion controllers should be as thin as possible.
Move chatHub.client.getOnlineUsers function to the service and create getter for users.
Further read

firebase current user id

I am getting an error retrieving current user id from my factory/service. Removing this firebase.auth().currentUser.uid seems to work.Am I missing something?Is it possible to get user id from factory?
.factory("dataFire", ["$firebaseArray", "$firebaseAuth", "$firebaseObject", function($firebaseArray, $firebaseAuth, $firebaseObject){
var ref = firebase.database().ref("users/" + firebase.auth().currentUser.uid);
var user = $firebaseObject(ref);
return {
user: user
} }])
jsfiddle link
https://jsfiddle.net/ken19net/m8qkdrpu/37/
Your code that attach the listener to the database, runs before the user is signed in. Since there is no current user at that point firebase.auth().currentUser.uid will throw the following error:
VM603 angular.min.js:118 TypeError: Cannot read property 'uid' of null
In future questions please include the error message, as it would've saved us both some time.
The solution is to attach the listener after the user has been authenticated:
app.controller("appCtrl", function($scope, $firebaseAuth, myService) {
$scope.signIn = function() {
$firebaseAuth().$signInAnonymously().then(function(user) {
var ref = firebase.database().ref("test/" + firebase.auth().currentUser.uid);
});
};
});
Note that running your code like above will create a new anonymous user account every time the user loads the page. If that is not what you want, use an auth state listener:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var ref = firebase.database().ref("test/" + firebase.auth().currentUser.uid);
}
});
See the documentation on getting the currently signed in user.
I might of had a similar problem. This might help.
if (firebase.auth().currentUser !== null) {
console.log("user id: " + firebase.auth().currentUser.uid);
var ref = firebase.database().ref().child("users/" + firebase.auth().currentUser.uid);
var syncUserObject = $firebaseObject(ref);
syncUserObject.$bindTo($scope, "data");
} else {
console.log("No user currently logged in");
}
if all else fails then just JSON.stringify(Object ,null, 2);

Firebase function not running until view change [duplicate]

This question already has an answer here:
How come Angular doesn't update with scope here?
(1 answer)
Closed 6 years ago.
I have a Firebase function inside an angular controller. There is a button that when clicked takes the selected option and the type input and stores them into the user's object like so:
{
selected-option : input-value
}
This works perfectly, but only works when the view is changed. In my case both airlines already have data so this function displays an $ionicPopup.
After the view has changed once the functionality is absolutely perfect. This is obviously a problem and I assume it is an $apply or $digest issue.
Here is my controller code (Supected location marked by "ISSUE RIGHT HERE"):
.controller('ProgramCtrl', ['$scope', '$state', '$firebaseArray', 'facebook', '$ionicPopup', '$ionicLoading',
function($scope, $state, $firebaseArray, facebook, $ionicPopup, $ionicLoading) {
$scope.goBack = function() {
$state.go('app.home');
}
$scope.show = function() {
$ionicLoading.show({
template: 'Loading...'
});
};
$scope.hide = function(){
$ionicLoading.hide();
};
// Get who is logged in
$scope.user = facebook.get();
// Array of airlines
var airRef = ref.child("airlines");
$scope.airlines = $firebaseArray(airRef);
$scope.selectedAir = {};
$scope.miles = {};
$scope.revealInput = function(num) {
// Jquery variables
$milesPoints = $(".milesPoints");
$saveTicket = $(".saveTicket");
// Will fade in visibility depending on num passed into function
switch(num) {
case 1:
$saveTicket.prop("disabled", false);
$saveTicket.fadeTo(400, 1);
break;
default:
break;
}
}
// Add program to user
$scope.addProgram = function () {
// Connect to Firebase
Firebase.goOnline();
// Check for facebook user
if(jQuery.isEmptyObject($scope.user)) {
// Get Firebase user
var authData = ref.getAuth();
var theUser = ref.child("users").child(authData.uid);
var selected = {};
// Access user miles data
// $scope.show();
// ISSUE RIGHT HERE
theUser.child("miles").child($scope.selectedAir.name.$id).once("value", function(snapshot) {
// Update scopes
var exist = snapshot.exists();
// Check if object id exists, if so notify user
if(!exist) {
// Save and update program to user object
selected[$scope.selectedAir.name.$id] = $scope.miles.num;
theUser.child("miles").update(selected);
//$scope.hide();
$state.go("app.saved");
} else {
// Popup alert
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "You already created this airline! Go to the 'Add Ticket' page to add more points."
});
alertPopup.then(function(res) {
console.log("You already created this airline! Go to the 'Add Ticket' page to add more points.");
});
}
})
} else {
var theUser = ref.child("users").child($scope.user.id);
var selected = {};
$scope.show();
theUser.child("miles").child($scope.selectedAir.name.$id).once("value", function(snapshot) {
var exist = snapshot.exists();
if(!exist) {
selected[$scope.selectedAir.name.$id] = $scope.miles.num;
theUser.child("miles").update(selected);
$scope.hide();
$state.go("app.saved");
} else {
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "You already created this airline! Go to the 'Add Ticket' page to add more points."
});
alertPopup.then(function(res) {
console.log("You already created this airline! Go to the 'Add Ticket' page to add more points.");
});
}
})
}
}
}])
Thanks for the help and I can provide more code or screenshots if needed.
The issue is in this piece of code:
theUser.child("miles").child($scope.selectedAir.name.$id).once("value", function(snapshot) {
$timout(function() {
var exist = snapshot.exists();
// Check if object id exists, if so notify user
if(!exist) {
// Save and update program to user object
selected[$scope.selectedAir.name.$id] = $scope.miles.num;
theUser.child("miles").update(selected);
//$scope.hide();
$state.go("app.saved");
} else {
// Popup alert
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "You already created this airline! Go to the 'Add Ticket' page to add more points."
});
alertPopup.then(function(res) {
console.log("You already created this airline! Go to the 'Add Ticket' page to add more points.");
});
}
});
})
When you call once(), it starts loading data from Firebase. Since this may take some time, you pass in a callback function that is invoked when the data is available. But by the time the callback function is invoked, AngularJS is not expecting updates to the $scope anymore.
The solution is to wrap the code into a $timeout(), which ensures it gets executed when AngularJS is ready to handle scope changes again:
theUser.child("miles").child($scope.selectedAir.name.$id).once("value", function(snapshot) {
// Update scopes
var exist = snapshot.exists();
// Check if object id exists, if so notify user
if(!exist) {
// Save and update program to user object
selected[$scope.selectedAir.name.$id] = $scope.miles.num;
theUser.child("miles").update(selected);
//$scope.hide();
$state.go("app.saved");
} else {
// Popup alert
var alertPopup = $ionicPopup.alert({
title: 'Oops!',
template: "You already created this airline! Go to the 'Add Ticket' page to add more points."
});
alertPopup.then(function(res) {
console.log("You already created this airline! Go to the 'Add Ticket' page to add more points.");
});
}
})
Note that this problem wouldn't happen if you used AngularFire's $firebaseObject() and $firebaseArray() primitives, since those automatically notify AngularJS of scope changes.
We get this question a lot. Here's a recent one: Taking long to load

$watch not updating when service object is updated

I have discovered a perplexing circumstance in which the $scope.watch is not triggering as I would expect. I am hoping some of you AngularJS buffs out there can help shed some light on why Angular is behaving so peculiarly with $scope.watch and Service objects. As a note this was discovered while I was messing with the Ionic framework.
Below is an example of what I am running, and it works as expected (to be used to maintain state information during the session.)
TL;DR:
Watch doesn't fire on the controller when I update currentUser with a new userObject (currentUser = new userObject();) in my service. It does fire if I instead update each individual attribute of the object.
currentUser.name = 'Foo';
currentUser.email = 'foo#bar.com';
I am seeking guidance on why so I can better understand.
Code
Service (Working)
angular.module('app.services')
.service( 'UserService', function() {
var userObject = function(){
return {
id: null,
username: null,
email: null,
fullName: null,
modified: null
}
};
var currentUser = new userObject();
var createUser = function(id, username, email, fullName, modified ){
var newUserObject = new userObject();
newUserObject.id = id;
newUserObject.username = username;
newUserObject.email = email;
newUserObject.fullName = fullName;
newUserObject.modified = (modified) ? modified : new Date();
return newUserObject;
};
var setCurrentUser = function(userObj){
console.log('First');
console.dir(currentUser);
setUserId(userObj.id);
setUsername(userObj.username);
setEmail(userObj.email);
setFullName(userObj.fullName);
setModifiedDate(userObj.modified);
console.log('Second');
console.dir(currentUser);
return currentUser;
};
});
Controller
angular.module('app.controllers')
.controller('DashboardCtrl', function ($scope, UserService) {
var dashboard = this;
dashboard.user = UserService.currentUser;
$scope.$watch('UserService.currentUser', function(newVal, oldVal) {
if (newVal !== oldVal ){
dashboard.user = newVal;
}
});
var createdUser = UserService.createUser(
1,
'user1',
'asdf#asdf.com',
'Test User',
new Date()
);
UserService.setCurrentUser(createdUser);
});
View
<div ng-controller="DashboardCtrl as dashboard">
<span bind="dashboard.user.fullName">Loading</span>
</div>
Result
WAHOO! Loading is replaced on init with '' (null) and immediately after it is updated by the watch with 'Test User' (faster than the human eye unless debugging)
Breaking Scenario
The code above works great. However I wanted to try and reduce code by reducing repetition of effort by creating a new UserObject and then setting that object as 'Current User'. The change I made was as follows (view and controller were unchanged):
Service (Broken)
angular.module('app.services')
.service( 'UserService', function() {
var userObject = function(){
return {
id: null,
username: null,
email: null,
fullName: null,
modified: null
}
};
var currentUser = new userObject();
var createUser = function(id, username, email, fullName, modified ){
var newUserObject = new userObject();
newUserObject.id = id;
newUserObject.username = username;
newUserObject.email = email;
newUserObject.fullName = fullName;
newUserObject.modified = (modified) ? modified : new Date();
return newUserObject;
};
var setCurrentUser = function(userObj){
console.log('First');
console.dir(currentUser);
// Set original 'currentUser' with a new UserObject passed by controller
currentUser = userObj;
console.log('Second');
console.dir(currentUser);
return currentUser;
};
});
Result
Loading is replaced with '' on init (null) and $scope.watch never triggers in this scenario. My expectation is that the watch should be doing a deep watch on the object, and when I replace the object with a new one it should trigger that the object changed and trigger the watch.
The only thing I can figure, is that when I replace the currentUser object with a new object is that the delegates for $watch are also lost on that object. Does anyone have insight on how I can tell?
Phew.
When you give a string to the $watch it checks that variable inside angular function, As you don't have UserService.currentUser inside your scope then that watcher function will never get fired.
For making your watch working, you need to use function instead of string, then that function will return an expression. By adding it in watcher function, so that it will get evaluated on each digest cycle & will perform dirty checking. If value gets change it will fire the watcher function
Code
$scope.$watch(function(){
return UserService.currentUser;
}, function(newVal, oldVal) {
if (newVal !== oldVal ){
dashboard.user = newVal;
}
});

When page refresh, how to call back function in angularjs

I'm trying to maintain session after page refresh in angularjs using java. I have seen many examples but, i didn't find proper solution which exactly I'm looking for.
Please find below login snippet code, when i click on login button it is calling loginUser()function in LoginController
When i do page refresh it is going to LoginController but it is not going inside loginUser()function.
According to my knowledge until we call function, it doesn't goes inside of it.
When I do refresh how can i call back loginUser() function.
please help me out from these. Appreciated..Many thanks.
LoginController.js
function LoginController($scope, $http, $location, $rootScope,
userService, SessionIdService) {
$scope.user = {};
$scope.user.username = '';
$scope.user.password = '';
$rootScope.loginUser = function(username, password) {
$scope.resetError();
$http.post('/user/main/login/' + username, password).success(
function(login) {
if (login.sessionId === null) {
$scope.setError(login.status);
return;
} else {
$rootScope.userlogin = login.uname;
userService.setUserName(login.uname);
SessionIdService.setSessionId(login.sessionId);
$location.path("/home");
}
}).error(function() {
$scope.setError('Invalid user/password combination');
});
};
$scope.resetError = function() {
$scope.error = false;
$scope.errorMessage = '';
};
$scope.setError = function(message) {
$scope.error = true;
$scope.errorMessage = message;
$rootScope.sees = '';
$rootScope.userlogin = '';
};
};
app.js
app.run(function($rootScope, $location, SessionIdService) {
$rootScope.$on("$routeChangeStart", function(event, next, current) {
console.log("Routechanged... ");
if (SessionIdService.getSessionId == "true") {
if (next.templateUrl == "scripts/views/homescreen.html") {
$location.path("/home");
} else {
$location.path("/screen");
}
}
});
});
login.html
<input name="textfield" type="text" ng-model="user.username"/>
<input name="textfield" type="password" ng-model="user.password"/>
<button type="button" ng-lick="loginUser(user.username,user.password)">Login</button>
It is not clear to me why you want to call loginUser after page refresh. Isn't the user already logged in? I think what you want is to call the success function inside the loginIser. In that case, you need to embed that data as a global JS variable inside your Java template, and pass that to your controller somehow.
You probably want these to be run after refresh:
$rootScope.userlogin = login.uname;
userService.setUserName(login.uname);
SessionIdService.setSessionId(login.sessionId);
$location.path("/home");
So, in your Java template, do something like:
<script>window.UNAME = {% this comes from your database %};window.SESSIONID={% similar %}</script>
Then, call that function somehow with window.UNAME as input. (or in your controller, check for the existence of window.UNAME and call it immediately. Something like:
window.UNAME && function (name, sessionId) {
$rootScope.userlogin = uname;
userService.setUserName(uname);
SessionIdService.setSessionId(sessionId);
$location.path("/home");
) {
}(window.UNAME, window.SESSION_ID)
Some other recommendations (unrelated to your main problem probably):
First of, change $rootScope.loginUser = function(username, password) { to
$rootScope.loginUser = function() {
var username = $scope.user.username;
var password = $scope.user.password
since you already have access to username and password there. So, change ng-click="loginUser()".
Second, SessionIdService.getSessionId == "true" seems off, check should probably be just SessionIdService.getSessionId

Resources