I'm trying to implement Firechat in angularJS and have come across a weird issue.
After the chat initialises the angular route changes to the Firechat room name.
e.g I am initially on http://localhost/app/#/stream
and when firechat loads the route changes to
http://localhost/app/#/-KBLofTk2mb6AJCTSc5C
I can't seem to figure out how or why firechat is changing the route. Any advice would be great :)
Here is the code I am using to run fireChat:
$scope.goFireChat = function() {
var chatRef = new Firebase('https://blazing-fire-3021.firebaseio.com'),
target = document.getElementById("firechat-wrapper"),
chat = new FirechatUI(chatRef, target);
chatRef.onAuth(function(authData) {
if (authData) {
var userId = authData.uid,
userName = "Anonymous" + userId.substr(10, 8);
chat.setUser(userId, userName);
$timeout(function() {
chat._chat.enterRoom('-KBLofTk2mb6AJCTSc5C');
}, 2000);
} else {
$timeout(function() {
chat._chat.enterRoom('-KBLofTk2mb6AJCTSc5C');
}, 2000);
}
});
}
Related
Hy every one!
I'm using in this project Angular 1.6.5 because my workteam think is better.
But I found an error with angular elements. In all forms of my app They stop the behaviour after a time. That is, it doesn't save date when i click in button save, ore delete. But when i refresh the page the elements start responds again. Any one have idea why?
In the project we are using a library to control style css. the problem may be there?
here is one piece of my html code
<div class="col-4-1">
<p class="link"><a class="btn-pri" href ng-click="savePartner()" ng-if="enableSaveBtn">Save</a></p>
<p class="link"><a class="btn-pri remove-link btn-red-50" href ng-click="delPartner()" ng-if="enableDelBtn">Erase</a></p>
</div>
pice controller code:
$scope.addLabelToPartner = function() {
$scope.partner.LabelList = $scope.partner.mcnList || [];
$scope.partner.LabelList.push($scope.partner.code);
$scope.partner.code = "";
};
$scope.delLabelFromPartner = function(idx) {
$scope.partner.LabelList.splice(idx, 1);
};
$scope.savePartner = function() {
$scope.saveErr = false;
WebService.createPartner($scope.partner).then(
function(response) {
common.widget.overlay.hide("overlayPartnerForm");
$scope.fetchAllPartners();
},
function(error) {
$scope.saveErr = true;
}
);
};
$scope.delPartner = function() {
$scope.saveErr = false;
WebService.deletePartner($scope.partner._id).then(
function(response) {
common.widget.overlay.hide("overlayPartnerForm");
$scope.fetchAllPartners();
},
function(error) {
$scope.saveErr = true;
}
);
};
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
I am trying to redirect to a specific job page when there's a new applicant.
Here's the code:
app.run(function($ionicPlatform, $location) {
$ionicPlatform.ready(function() {
if (ionic.Platform.isWebView()) {
window.plugins.OneSignal
.startInit("xxxxxxxxxxxxxx", "xxxxxxxxxxxx")
.handleNotificationReceived(function(jsonData) {
console.log("/app/upcoming/" + jsonData.payload.additionalData.url);
$location.path("/app/upcoming/" + jsonData.payload.additionalData.url);
})
.endInit();
}
The console shows the correct address but it does not redirect or have any errors.
For Ionic you will need to use $state.go to redirect the user to a different page in your app.
var notificationOpenedCallback = function(result) {
var data = result.notification.payload.additionalData;
if (data && data.targetUrl) {
var state = $injector.get($state);
state.go(data.targetUrl);
}
};
window.plugins.OneSignal
.startInit("YOUR_APPID", "YOUR_GOOGLE_PROJECT_NUMBER_IF_ANDROID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
I'm an atmosphere & Angular newbie and I'm really struggling to find an answer to this! Maybe I'm asking the wrong question.
I am setting up notifications using Atmosphere. I can open the websocket and watch the updates happen if I post the API URL directly into my browser.
In Angular I have an ng-repeat loop, which I would like to run as each new update adds a new object to the websocket.
<li ng-repeat="notification in notifications track by $index">
I am using angular watch to check for updates, but it doesn't pick up the new objects being added to the array. Here is my code:
// notification alerts
$scope.notifications = [];
notificationsService.notificationAlerts().then(function success(response) {
var jsonStringArray = response.data.split('|');
$scope.notifications = $.map(jsonStringArray, function(n, i){
if (n !== ""){
return JSON.parse(n);
}
});
console.log('Connect', response);
});
$scope.$watch('notifications', function(newVal, oldVal){
console.log('Watch', $scope.notifications);
}, true);
Hopefully I've made myself clear, let me know if I need to elaborate, or if I'm asking the wrong question. Thanks!
OK, I managed to solve this, for anyone stumbling across it later. Here is the final JS:
// add number of notifications to ".notifications-number"
function updateNumberOfNotifications(){
var numberOfNotifications = $("ul.notifications-list li").not(".nocount").length;
if (numberOfNotifications < 1) {
$(".notifications-number, .notifications-list").addClass("hidden");
} else {
$(".notifications-number").html(numberOfNotifications);
$(".notifications-number, .notifications-list").removeClass("hidden");
}
}
// notification alert variables
$scope.notifications = [];
var socket = atmosphere;
var subSocket;
// subscribe
function subscribe() {
var request = {
url : "/service/notifier",
transport: 'long-polling'
};
request.onMessage = function (response) {
//console.log('response', response);
var jsonStringArray = response.responseBody.split('|');
// console.log('json string array', jsonStringArray);
$.each(jsonStringArray, function(index, elem){
if (elem != ""){
$scope.notifications.push(JSON.parse(elem));
console.log("object", JSON.parse(elem));
}
});
//$scope.notifications.push($scope.newNotification);
$scope.$apply();
updateNumberOfNotifications();
// console.log('$scope.notifications', $scope.notifications);
};
subSocket = socket.subscribe(request);
}
function unsubscribe(){
socket.unsubscribe();
}
// subscribe on load and update notifications
updateNumberOfNotifications();
subscribe();
In app.js I have a variable that I use in two files/controllers:
var app = angular.module('appDemo', ['MainControllers', 'MainServices'])
.constant('myConfig', {
'backend': 'http://localhost:1236'
})
.service('mailService', function() {
var mail = {
value: 'hello world'
};
var getMail = function() {
return mail;
}
var setMail = function(email) {
mail.value = email;
}
return {
getMail: getMail,
setMail: setMail
};
);
Setting the variable from controllerOne goes fine:
angular.module('MainControllers')
.controller('MemberController', function ($scope, mainService, appDemo) {
window.onbeforeunload = function (e) {
appDemo.setMail('test#test.com');
};
But when I get the setting variable from the controllerTwo than I get the default value:
angular.module('MainControllers')
.controller('EmailController', function($scope, appDemo) {
$scope.mailAddress = appDemo.getMail();
});
Each controller is in separate file.
what is wrong?
This may be because the service itself is being reloaded because as I can see you are setting the mail in the first controller on onbeforeunload.
Services can't persist on window reloads or page refresh. They get reloaded hence reinitialized every time you reload the page.
If you want to persist the values try putting it in localStorage or sessionStorage.