-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.js
More file actions
53 lines (51 loc) · 1.8 KB
/
controller.js
File metadata and controls
53 lines (51 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
AngularJS 部分
*/
// 設定 ng-app 名稱為 FirebaseChat
var app = angular.module("FirebaseChat", []);
// 設定 FirebaeChat 的 Controller 名為 ChatController
app.controller("ChatController", function($scope) {
// chatMessages 為訊息陣列
$scope.chatMessages = [];
/* 這裡用來讀取 Firebase 中的聊天訊息 */
var chatData = firebase.database().ref('chats');
chatData.on('value', function(snapshot) {
$scope.chatMessages = []
for (i in snapshot.val()) {
firebase.database().ref('chats/' + i).once('value', function(result) {
var data = result.val()
$scope.addMessage(data["sender"], data["message"], data["time"]);
$scope.$apply();
var elem = document.getElementById('scrollPanel');
elem.scrollTop = elem.scrollHeight;
});
}
});
// 聊天訊息的格式
$scope.formatChat = function(username, text, time) {
var chat = {};
chat.username = username;
chat.text = text;
chat.time = time;
return chat;
}
// 新增聊天訊息到 html 當中
$scope.addMessage = function(username, text, time) {
var chat = $scope.formatChat(username, text, new Date(time));
$scope.chatMessages.push(chat)
}
// 新增訊息到 Firebase 當中
$scope.addChat = function() {
if ($scope.newChatMsg != "" && $scope.username != "") {
sendMessage($scope.username, $scope.newChatMsg, new Date().toString())
$scope.newChatMsg = "";
} else {
alert("請輸入完整訊息!")
}
}
});
app.filter('reverse', function() {
return function(items) {
return items.slice().reverse();
};
});